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 Read more…

CountdownLatch

Explain CountDownLatch using real life problem? Let me try to explain CountDownLatch with some real life example: Consider you 5 rooms in your house. Your father is at home with 5 servants, and you are calling from office to your father to ask him to check if you have switched Read more…

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 Read more…

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 Read more…

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 Read more…

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 Read more…