Last active
May 5, 2024 14:20
-
-
Save sshark/a2bfea7be6b03b88ed0fcbab83b5cc50 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.* | |
def delay(delay: Long)(id: String) = Future { | |
Thread.sleep(delay) | |
println(s"$id done") | |
id | |
} | |
def fast(id: String) = delay(500)(id) | |
def slow(id: String) = delay(1000)(id) | |
def firstA = List(fast("A"), slow("B"), slow("C")) | |
def lastA = List(slow("B"), slow("C"), fast("A")) | |
Future.firstCompletedOf(firstA).foreach(x => println(s"### $x")) | |
Future.firstCompletedOf(lastA).foreach(x => println(s"### $x")) | |
/* | |
final def firstCompletedOf[T](futures: IterableOnce[Future[T]])(implicit executor: ExecutionContext): Future[T] = { | |
val i = futures.iterator | |
if (!i.hasNext) Future.never | |
else { | |
val p = Promise[T]() | |
val firstCompleteHandler = new AtomicReference[Promise[T]](p) with (Try[T] => Unit) { | |
override final def apply(v1: Try[T]): Unit = { | |
val r = getAndSet(null) | |
if (r ne null) | |
r tryComplete v1 // tryComplete is likely to be cheaper than complete | |
} | |
} | |
while(i.hasNext && firstCompleteHandler.get != null) // exit early if possible | |
i.next().onComplete(firstCompleteHandler) | |
p.future | |
} | |
} | |
*/ | |
// https://www.politico.com/news/magazine/2024/05/03/college-campus-protests-israel-gaza-student-journalists-00155672?utm_medium=10today.us.sat.rd.20240504.436.1&utm_source=email&utm_content=article&utm_campaign=email-2022 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment