Java Concurrency

Java Concurrency

Golden Rules

  1. Make it right
  2. Make it fast

Approach for this

  1. Try to move the locks as lower as possible
  2. Try to be thread-safe (use only immutable or no states at all)

KeyWords: Race Condition: Multiple threads are trying to acquire the resources.

Data Race: Typically check and update kind of cases where, the date that got modified is up for access immidiatly for update and read.

Main components

  • Executor
  • ExecutorService
  • ScheduledExecutorService
  • Future
  • CountDownLatch
  • CyclicBarrier
  • Semaphore
  • ThreadFactory
  • BlockingQueue
  • DelayQueue
  • Locks
  • Phaser

Life Cycle of Thread

image-title-here

Java.util.concurrent

The Interfaces in this package are classified on prilimnary levels as collection related and concurrency tools & mechanisms:

Collection Related Interfaces
TransferQueue
ConcurrentMap
ConcurrentNavigableMap
BlockingDeque
BlockingQueue
Concurrency Tools & Mechanisms
Callable
CompletableFuture.AsynchronousCompletionTask
CompletionService
CompletionStage
Delayed
Executor
ExecutorService
ForkJoinPool.ForkJoinWorkerThreadFactory
ForkJoinPool.ManagedBlocker
Future
RejectedExecutionHandler
RunnableFuture
RunnableScheduledFuture
ScheduledExecutorService
ScheduledFuture
ThreadFactory

The classes in this package are classified on prilimnary levels collection and concurrency tools & mechanisms;

Concurrency Handling Concurrent Collection
AbstractExecutorService ArrayBlockingQueue
CompletableFuture ConcurrentHashMap
CountDownLatch ConcurrentHashMap.KeySetView
CountedCompleter ConcurrentLinkedDeque
CyclicBarrier ConcurrentLinkedQueue
Exchanger ConcurrentSkipListMap
ExecutorCompletionService ConcurrentSkipListSet
Executors CopyOnWriteArrayList
ForkJoinPool CopyOnWriteArraySet
ForkJoinTask DelayQueue
ForkJoinWorkerThread LinkedBlockingDeque
FutureTask LinkedBlockingQueue
Phaser LinkedTransferQueue
RecursiveAction PriorityBlockingQueue
RecursiveTask SynchronousQueue
ScheduledThreadPoolExecutor  
Semaphore  
ThreadLocalRandom  
ThreadPoolExecutor  
ThreadPoolExecutor.AbortPolicy  
ThreadPoolExecutor.CallerRunsPolicy  
ThreadPoolExecutor.DiscardOldestPolicy  
ThreadPoolExecutor.DiscardPolicy  

Lets take a closer look at those in Concurrency Handling column and try to re-classify them into differnt groups.

Collection

image-title-here

Future Flow

image-title-here

Executor Flow

image-title-here

CountDownLatch

image-title-here

Exchanger

image-title-here

Phaser

image-title-here

Remaining tools

  • CyclicBarrier
  • Executors
  • Phaser
  • Semaphore
  • ThreadLocalRandom
  • ForkJoinWorkerThread
  • CompletionService