Skip to main content

Posts

Showing posts with the label concurrency

Understanding Concurrency, Threading and Synchronization

Thread: A thread is defined at the operating system level. It is a single execution of a program. A thread is a set of instruction. An application can be composed of several threads. Different threads can be executed at the same time. The JVM works with several threads like Garbage collector, JIT etc. What does mean by "At the same time"? In a single core of CPU, the threads cannot works at the same time, it give us a feel that it is running at same but in reality it work one by one and the context switch happen very fast in milliseconds which we can't observe. On a multi-core CPU, things happens at the same time. A challenge while this is the read and write operation involve while running different thread at same time. Who is responsible for the CPU sharing? There is a special element who does this, is called scheduler.there are three reasons for a scheduled to pause a thread -  The CPU should be shared equally among threads. The thread might be waiting ...

Semaphore in java

A  Semaphore  is a thread synchronization mechanism that can be used - To send signals between threads To guard a critical section for enforcing limited access to the resource Semaphore in java come with java 1.5 and available under package "java.util.concurrent"  Below is an example which you can go through to understand how we can enforce a limited number of thread to access a particular section of code at a time. import java.util.concurrent.Semaphore; public class SemaphoreExample { Semaphore semaphore = new Semaphore(2); private void printLock() { try { semaphore.acquire(); System.out.println("Lock acquired by "+Thread.currentThread().getName()); System.out.println("Locks remaining "+semaphore.availablePermits()); Thread.sleep(5000); } catch (InterruptedException ie) { ie.printStackTrace(); } finally { semaphore.release(); System.out.println("Locks release "+Thread.cur...