May 15, 2018 by Sandeep Bhardwaj | Tags: Java Concurrency
Lock.java public class Lock { private boolean isLocked = false; public synchronized void lock() throws InterruptedException { while (isLocked) { wait(); } isLocked = true; } public synchronized void unlock() { isLocked = false; notify(); } } Usage lock.lock(); try { // .....
Read moreMay 13, 2018 by Sandeep Bhardwaj | Tags: Java
Singleton.java public class Singleton { private static volatile Singleton _instance; // volatile variable private Singleton(){} //private constructor public static Singleton getInstance() { if (_instance == null) { synchronized (Singleton.class) { if (_instance == null) _instan...
Read moreMay 06, 2018 by Sandeep Bhardwaj | Tags: Java Concurrency
CyclicBarrierExample.java import java.util.concurrent.CyclicBarrier; public class CyclicBarrierExample { public static void main(String[] args) { CyclicBarrier barrier = new CyclicBarrier(3, new BarrierAction()); new Thread(new Party(barrier)).start(); new Thread(new Party(barrier)).st...
Read moreApril 03, 2017 by Sandeep Bhardwaj | Tags: Java Concurrency
SemaphoreExample.java import java.util.concurrent.Semaphore; public class SemaphoreExample { public static void main(String[] args) { Semaphore semaphore = new Semaphore(2); new Thread(new Task(semaphore)).start(); new Thread(new Task(semaphore)).start(); new Thread(new Task(semaphor...
Read moreApril 02, 2017 by Sandeep Bhardwaj | Tags: Java Concurrency
ThreadPool.java Custom ThreadPool class with using the LinkedBlockingQueue for holding the incoming threads. import java.util.concurrent.LinkedBlockingQueue; public class ThreadPool { volatile boolean isRunning; private LinkedBlockingQueue<Runnable> blockingQueue; private WorkerThread[...
Read more