Skip to content

Instantly share code, notes, and snippets.

@martiner
Created March 11, 2016 13:16
Show Gist options
  • Save martiner/119cbf1a41b103dd3f71 to your computer and use it in GitHub Desktop.
Save martiner/119cbf1a41b103dd3f71 to your computer and use it in GitHub Desktop.
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class TrueStory {
private static final int SLEEP = 1;
private final int count = 10;
private final ExecutorService service = Executors.newFixedThreadPool(count);
private final long start = System.currentTimeMillis();
public static void main(String[] args) throws Exception {
final TrueStory trueStory = new TrueStory();
final List<Integer> result = trueStory.process();
System.out.println(trueStory.elapsedSeconds());
trueStory.service.shutdown();
}
private List<Integer> process() {
return IntStream.range(0, count)
.boxed()
.map(i -> service.submit(() -> doIt(i)))
.map(TrueStory::extractFuture)
.flatMap(TrueStory::stream)
.collect(Collectors.toList());
}
private Integer doIt(final int value) throws Exception {
TimeUnit.SECONDS.sleep(SLEEP);
return value;
}
static Optional<Integer> extractFuture(final Future<Integer> future) {
try {
return Optional.of(future.get());
} catch (InterruptedException | ExecutionException e) {
return Optional.empty();
}
}
static <T> Stream<T> stream(final Optional<T> value) {
return value.map(Stream::of).orElse(Stream.empty());
}
private int elapsedSeconds() {
return (int)Math.floor((System.currentTimeMillis() - start) / 1_000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment