Show Menu
Cheatography

Java8 Multithreading Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Basics - Implement Runnable

 
Runnable runnable = () -> { / code here /}

Thread thread = new Thread­(ru­nna­ble);

thread.st­art();

Basics - Executor

shutdown()
Waits for currently running tasks to finish
shutdo­wnNow()
Interrupts all running tasks and shut the executor down immedi­ately
awaitT­erm­ina­tion(5, TimeUn­it.S­EC­ONDS)
Waits a certain amount of time for termin­ation of currently running tasks. After a max of 45 seconds, the executor finally shuts down by interr­upting all tasks
Callables and Futures
Callable are like runnables but return a value.
Execut­orS­ervice executor = Execut­ors.ne­wSi­ngl­eTr­ead­Exe­cut­or();

execut­or.s­ub­mit(() -> { / Code / });
   

Avoiding Deadlocks

Ensure all threads use same order
If all threads try to get the locks in the same order, a deadlock will not occur
Timeout / Retry
Put a timeout with a retry mechanism when obtaining locks
Wait
Can only be called from within synchr­onized block (must have the lock to call). Once wait is called, all locks are released
Notify
NotifyAll
Deadlocks occur when multiple threads need the same locks but obtain them in a different order