Skip to content

Instantly share code, notes, and snippets.

@schatterjee4
Forked from bdelacretaz/Lambdastuff.java
Created May 3, 2018 06:27
Show Gist options
  • Save schatterjee4/1c2e81b66fee23d2c45fe051d7ce60fd to your computer and use it in GitHub Desktop.
Save schatterjee4/1c2e81b66fee23d2c45fe051d7ce60fd to your computer and use it in GitHub Desktop.
Example with Java 8 Lamdbam executors and futures
package lamdbastuff;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
public class Lamdbastuff {
static int failed;
static boolean debug = false;
static Callable<String> longRunningTask(Semaphore s, int i) {
return () -> {
final long start = System.currentTimeMillis();
boolean permit = false;
try {
permit = s.tryAcquire(350, TimeUnit.MILLISECONDS);
TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextInt(10, 25));
if (permit) {
TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextInt(50, 250));
} else {
failed++;
}
} catch (InterruptedException e) {
throw new IllegalStateException(e);
} finally {
if (permit) {
s.release();
}
}
return "Task " + i + (permit ? " was executed and took " : " was NOT executed but took ") + (System.currentTimeMillis() - start) + " msec";
};
}
public static void main(String args[]) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(10);
Semaphore semaphore = new Semaphore(3);
final List<Future<String>> fut = new ArrayList<>();
IntStream.range(0, 10).forEach(i -> fut.add(executor.submit(longRunningTask(semaphore, i))));
while(!fut.isEmpty()) {
for(Iterator<Future<String>> it = fut.iterator() ; it.hasNext() ; ) {
Future<String> f = it.next();
if(f.isDone()) {
System.out.println(f.get());
it.remove();
}
}
TimeUnit.MILLISECONDS.sleep(100);
}
System.out.println("failed=" + failed);
executor.shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment