Skip to content

Commit 07fa1d5

Browse files
committed
Move findFirst in FutureUtils and use AtomicInteger instead of synchronized
1 parent f0d7652 commit 07fa1d5

File tree

3 files changed

+32
-24
lines changed

3 files changed

+32
-24
lines changed

src/main/scala/inox/solvers/combinators/PortfolioSolver.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ trait PortfolioSolver extends Solver { self =>
5858
}
5959
}
6060

61-
inox.utils.findFirst(fs)(_._2 != Unknown) match {
61+
inox.utils.FutureUtils.findFirst(fs)(_._2 != Unknown) match {
6262
case Some((s, r)) =>
6363
resultSolver = s.getResultSolver
6464
resultSolver.foreach { solv =>
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/* Copyright 2009-2021 EPFL, Lausanne */
2+
3+
package inox.utils
4+
5+
import scala.util._
6+
import scala.concurrent._
7+
import scala.concurrent.duration._
8+
import scala.concurrent.ExecutionContext.Implicits.global
9+
import java.util.concurrent.atomic.AtomicInteger
10+
11+
object FutureUtils {
12+
13+
def findFirst[T](futures: Seq[Future[T]])(cond: T => Boolean): Option[T] = {
14+
val p = Promise[Option[T]]()
15+
val n = futures.length
16+
val i = new AtomicInteger(0)
17+
18+
for (future <- futures) {
19+
future.onComplete((result: Try[T]) => result match {
20+
case Success(res) if cond(res) =>
21+
p.trySuccess(Some(res))
22+
case _ =>
23+
synchronized { i.getAndIncrement() }
24+
if (i.get == n) p.trySuccess(None)
25+
})
26+
}
27+
Await.result(p.future, Duration.Inf)
28+
}
29+
30+
}

src/main/scala/inox/utils/package.scala

Lines changed: 1 addition & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,6 @@
22

33
package inox
44

5-
import scala.util._
6-
import scala.concurrent._
7-
import scala.concurrent.duration._
8-
import scala.concurrent.ExecutionContext.Implicits.global
9-
105
/** Various utilities used throughout the Inox system */
116
package object utils {
127

@@ -31,22 +26,5 @@ package object utils {
3126
}
3227
v2
3328
}
34-
35-
def findFirst[T](futures: Seq[Future[T]])(cond: T => Boolean): Option[T] = {
36-
val p = Promise[Option[T]]()
37-
val n = futures.length
38-
var i = 0
39-
40-
for (future <- futures) {
41-
future.onComplete((result: Try[T]) => result match {
42-
case Success(res) if cond(res) =>
43-
p.trySuccess(Some(res))
44-
case _ =>
45-
synchronized { i += 1 }
46-
if (i == n) p.trySuccess(None)
47-
})
48-
}
49-
Await.result(p.future, Duration.Inf)
50-
}
51-
29+
5230
}

0 commit comments

Comments
 (0)