Semaphore in Java

What is semaphore? Lets first talk about definition of semaphore we have read in our Operating System books: Semaphore is a counter (integer) value with help of which, process allows a thread to get into a critical region. If the value of the counter is greater than 0, the counter is decremented by one and…

Wait, Notify And NotifyAll in Java

What is the use of wait() method? It causes the current thread to go to leave the lock and go to waiting state. What is the use of notify() and notifyAll() method? notify() Causes one of the threads waiting on same object to leave the waiting state and go to runnable state. So if we…

Compare And Swap in Java

How is the traditional way to control access to shared variables in java? The traditional way to control access to shared fields is to use synchronization. In synchronization, once the thread gets the lock, it gets exclusive access to the block of code. What are the short comings of traditional way to control access? There…

Synchronization

Why multiple threads corrupt data? Threads created in java uses processor-registers and per-processor caches to speed up memory access which gives good performance advantages and for the same reasons memory operations is not immediately visible to all other threads. As a result thread might be working on data which is updated by another thread but…

Ideal Thread Pool Size

Why correct size of Thread Pool is important? Tuning the size of a thread pool is largely a matter of avoiding two mistakes: having too few threads or too many threads. Too many threads can degrade performance because when CPU switches from one thread to another there is overhead of context switching. Processor utilization is…

ThreadLocal in Java

What is Thread Local? Values stored in these variables are local to threads, which mean that each thread puts and gets its own variable value. Lets see one example: Output: Thread-0 stored [Thread-0] in local and [Thread-0] in class variable Thread-1 stored [Thread-1] in local and [Thread-1] in class variable Thread-0 pulled [Thread-0] from local…

Lock Interface In Java

What is Lock Interface? Lock provides the same functionality as a synchronized block. Like synchronized, a lock is a tool for controlling access to a critical region by multiple threads. Example using synchronized block: Example using Lock class: Note: how lock() and unlock() methods are called on Lock object to secure critical region. Why is…