Java threading concepts
To spawn a new Thread, get it executed as independent path of execution. One need 3 things :
- Task - in the form of Runnable implementation
- Worker - a Thread class object
- Assigning task to the Worker - Passing task to the worker & invoking t.start()
// java8 way to create a thread - Providing Runnable interface implementation using lambda expression
Thread t1 = new Thread(() -> System.out.println("Creating a thread using lambda expression"));
t1.start();
A thread can be in one of the following states:
- NEW
- RUNNABLE
- BLOCKED
- WAITING
- TIMED_WAITING
- TERMINATED
- Thread.MIN_PRIORITY = 1
- Thread.NORM_PRIORITY = 5
- Thread.MAX_PRIORITY = 10
- Daemon threads are low-priority threads that conduct supporting tasks, whereas
- Non-Daemon threads are high-priority threads that handle particular tasks
The purpose of daemon threads is serving user threads, there’s no need to keep daemon threads running if all user threads terminate. That’s why the JVM will exit if there are only daemon threads running.
- t.join()
- t.interrupt()
- Thread.sleep()
- Thread.yield()
Thread interrupts - Interrupts are co-operative mechanism for indicating stop signal to a thread ( java.lang.InterruptedException )
- Mutual-Exclusion - sharing single resource across multiple threads
Once can achieve the synchronization effect in two ways :
- By synchronized method
- By synchronized bocks
And the Synchronized object lock could be
- Object level lock - instance method / block
- Class level lock - static method / block
- data race - read write problem
- deadlock
- wait
- notify()
- notifyAll()
- specific exception handler for each of the thread
- generic exception handler for all of the thread
Exploring java concurrent Package
-
java.util.concurrent.locks.Lock
-
java.util.concurrent.locks.ReentrantLock
-
java.util.concurrent.locks.ReadWriteLock
-
java.util.concurrent.locks.ReentrantReadWriteLock
-
CopyOnWriteArrayList
-
CopyOnWriteArraySet
-
BlockingQueue
-
ArrayBlockingQueue
-
LinkedBlockingQueue
-
ConcurrentHashMap
- Executors.newSingleThreadExecutor();
- Executors.newFixedThreadPool(1);
- Executors.newCachedThreadPool();
- ForkJoinPool
- Semaphore - a synchronizer to maintains set of permits
- CountDownLatch
- CyclicBarrier
- SynchronousQueue
- Exchanger
- Phaser