Writing concurrent code that is also correct is unbelievably hard. Naturally, humanity has developed a number of approaches to handle concurrency in the code, starting from basic threads that follow the hardware way to do concurrency to higher level primitives like fibers and work-stealing solutions. But which approach is the best for you? In this session, we'll take a look at a simple concurrent problem and solve it using different ways to manage concurrency: threads, executors, actors, fibers, monadic code with completable futures. All these approaches are different from the simplicity, readability, configuration and management point of view. Some scenarios are better modelled with threads, while sometimes you're better off with actors. We'll discuss the benefits of each approach and figure out when it's worth pursuing in your project.
17. THREADS
private static String getFirstResult(String question,
List<String> engines) {
AtomicReference<String> result = new AtomicReference<>();
for(String base: engines) {
String url = base + question;
new Thread(() -> {
result.compareAndSet(null, WS.url(url).get());
}).start();
}
while(result.get() == null); // wait for the result to appear
return result.get();
}
18. THREAD SAFETY
A piece of code is thread-safe if it only
manipulates shared data structures in
a manner that guarantees safe
execution by multiple threads at the
same time.
https://en.wikipedia.org/wiki/Thread_safety
34. FORK JOIN FRAMEWORK
Method
Async execution execute(ForkJoinTask)
Await and get result invoke(ForkJoinTask)
Exec and get Future submit(ForkJoinTask)
35. FORK JOIN POOL
private static String getFirstResult(String question,
List<String> engines) {
// get element as soon as it is available
Optional<String> result = engines.stream()
.parallel().map((base) ->
{
String url = base + question;
return WS.url(url).get();
}).findAny();
return result.get();
}
36. TAKEAWAY: FORK JOIN POOL
Efficient
Preconfigured
Easy to get right
Easy to get wrong
56. Seven Concurrency
Models in Seven
Weeks:
When Threads Unravel
by Paul Butcher
https://pragprog.com/book/pb7con/seven-concurrency-models-in-seven-weeks