Created
January 20, 2022 00:01
-
-
Save chrisxaustin/8f1f77dca017691434bc6dcb809e2301 to your computer and use it in GitHub Desktop.
Semaphore example
This file contains hidden or 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
package example; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.Semaphore; | |
import java.util.concurrent.TimeUnit; | |
import java.util.concurrent.atomic.LongAdder; | |
import java.util.stream.IntStream; | |
public class WithSemaphore { | |
public static void main(String[] argv) throws Exception { | |
var s = IntStream.range(0, 100_000) | |
.mapToObj(x -> Integer.toString(x)) | |
.spliterator(); | |
var exec = Executors.newFixedThreadPool(10); | |
var semaphore = new Semaphore(10); | |
var processed = new LongAdder(); | |
var start = System.currentTimeMillis(); | |
while (true) { | |
List<String> batch = new ArrayList<>(1000); | |
for (int i = 0; i < 1000 && s.tryAdvance(batch::add); i++) { | |
} | |
if (batch.isEmpty()) { | |
System.out.println("empty batch - done"); | |
break; | |
} | |
System.out.println("adding a batch"); | |
semaphore.acquire(); | |
exec.submit(() -> { | |
System.out.println("processing batch"); | |
try { | |
TimeUnit.SECONDS.sleep(1); | |
} | |
catch (InterruptedException e) { | |
e.printStackTrace(); | |
Thread.currentThread().interrupt(); | |
} | |
processed.increment(); | |
semaphore.release(); | |
}); | |
} | |
System.out.println("outside the loop"); | |
exec.shutdown(); | |
exec.awaitTermination(10, TimeUnit.SECONDS); | |
System.out.printf("processed %d batches in %ds\n", processed.sum(), (System.currentTimeMillis() - start) / 1000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment