Skip to content

Commit fe1d8fe

Browse files
committed
optimized Component.doInit
1 parent 432f1ed commit fe1d8fe

File tree

1 file changed

+21
-18
lines changed

1 file changed

+21
-18
lines changed

commons-core/src/main/scala/com/avsystem/commons/di/Component.scala

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -114,26 +114,29 @@ final class Component[+T](
114114
* NOTE: the component is initialized only once and its value is cached.
115115
*/
116116
def init(implicit ec: ExecutionContext): Future[T] =
117-
doInit(Nil, starting = true)
118-
119-
private def doInit(stack: List[Component[_]], starting: Boolean)(implicit ec: ExecutionContext): Future[T] = {
120-
val promise = Promise[T]()
121-
if (storage.compareAndSet(null, promise.future)) {
122-
if (starting) {
123-
validate()
124-
}
125-
val newStack = this :: stack
126-
val resultFuture =
127-
Future.traverse(dependencies)(_.doInit(newStack, starting = false))
128-
.flatMap(resolvedDeps => create(resolvedDeps)(ec))
129-
.recoverNow {
130-
case NonFatal(cause) =>
131-
throw ComponentInitializationException(this, cause)
117+
doInit(starting = true)
118+
119+
private def doInit(starting: Boolean)(implicit ec: ExecutionContext): Future[T] =
120+
storage.getPlain match {
121+
case null =>
122+
val promise = Promise[T]()
123+
if (storage.compareAndSet(null, promise.future)) {
124+
if (starting) {
125+
validate()
132126
}
133-
promise.completeWith(resultFuture)
127+
val resultFuture =
128+
Future.traverse(dependencies)(_.doInit(starting = false))
129+
.flatMap(resolvedDeps => create(resolvedDeps)(ec))
130+
.recoverNow {
131+
case NonFatal(cause) =>
132+
throw ComponentInitializationException(this, cause)
133+
}
134+
promise.completeWith(resultFuture)
135+
}
136+
storage.get()
137+
case future =>
138+
future
134139
}
135-
storage.get()
136-
}
137140
}
138141
object Component {
139142
def async[T](definition: => T): ExecutionContext => Future[T] =

0 commit comments

Comments
 (0)