Skip to content

Commit

Permalink
Replace synchronized blocks with virtual-thread-friendly Lock in Futu…
Browse files Browse the repository at this point in the history
…re.find() (#2910)

I replaced synchronized blocks with `Lock` because of virtual threads.

More details: https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html#GUID-04C03FFC-066D-4857-85B9-E5A27A875AF9

Similar to #2845
  • Loading branch information
Koziolek authored Oct 15, 2024
1 parent 1c00db1 commit 7508892
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion vavr/src/main/java/io/vavr/concurrent/Future.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.*;

/**
Expand Down Expand Up @@ -178,8 +180,10 @@ static <T> Future<Option<T>> find(Executor executor, Iterable<? extends Future<?
return run(executor, complete -> {
final AtomicBoolean completed = new AtomicBoolean(false);
final AtomicInteger count = new AtomicInteger(list.length());
final Lock lock = new ReentrantLock();
list.forEach(future -> future.onComplete(result -> {
synchronized (count) {
lock.lock();
try {
// if the future is already completed we already found our result and there is nothing more to do.
if (!completed.get()) {
// when there are no more results we return a None
Expand All @@ -193,6 +197,8 @@ static <T> Future<Option<T>> find(Executor executor, Iterable<? extends Future<?
}
});
}
} finally {
lock.unlock();
}
}));
});
Expand Down

0 comments on commit 7508892

Please sign in to comment.