Tutorial by Examples

If you have many tasks to execute, and all these tasks are not dependent of the result of the precedent ones, you can use Multithreading for your computer to do all this tasks at the same time using more processors if your computer can. This can make your program execution faster if you have some bi...
A simple example of producer-consumer problem solution. Notice that JDK classes (AtomicBoolean and BlockingQueue) are used for synchronization, which reduces the chance of creating an invalid solution. Consult Javadoc for various types of BlockingQueue; choosing different implementation may drastica...
A useful tool in Java Concurrency is ThreadLocal – this allows you to have a variable that will be unique to a given thread. Thus, if the same code runs in different threads, these executions will not share the value, but instead each thread has its own variable that is local to the thread. For exa...
CountDownLatch A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the count...
In Java, there is a built-in language-level locking mechanism: the synchronized block, which can use any Java object as an intrinsic lock (i.e. every Java object may have a monitor associated with it). Intrinsic locks provide atomicity to groups of statements. To understand what that means for us, ...
An atomic operation is an operation that is executed "all at once", without any chance of other threads observing or modifying state during the atomic operation's execution. Lets consider a BAD EXAMPLE. private static int t = 0; public static void main(String[] args) { ExecutorSe...
A deadlock occurs when two competing actions wait for the other to finish, and thus neither ever does. In java there is one lock associated with each object. To avoid concurrent modification done by multiple threads on single object we can use synchronized keyword, but everything comes at a cost....
Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. There are two overloaded sleep methods in the Thr...
As we know that we should use synchronized keyword to make execution of a method or block exclusive. But few of us may not be aware of one more important aspect of using synchronized and volatile keyword: apart from making a unit of code atomic, it also provides read / write barrier. What is this re...
There are two main approaches to creating a thread in Java. In essence, creating a thread is as easy as writing the code that will be executed in it. The two approaches differ in where you define that code. In Java, a thread is represented by an object - an instance of java.lang.Thread or its subcl...
Each Java Thread has an interrupt flag, which is initially false. Interrupting a thread, is essentially nothing more than setting that flag to true. The code running on that thread can check the flag on occasion and act upon it. The code can also ignore it completely. But why would each Thread have...
Below code showcases multiple Producer/Consumer program. Both Producer and Consumer threads share same global queue. import java.util.concurrent.*; import java.util.Random; public class ProducerConsumerWithES { public static void main(String args[]) { BlockingQueue<Integer> ...
It is sometimes required for a process to concurrently write and read the same "data". The ReadWriteLock interface, and its ReentrantReadWriteLock implementation allows for an access pattern that can be described as follow : There can be any number of concurrent readers of the data. If...
The Runnable interface defines a single method, run(), meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor. And Thread's start() method is called. Example public class HelloRunnable implements Runnable { @Override public void run()...
A Semaphore is a high-level synchronizer that maintains a set of permits that can be acquired and released by threads. A Semaphore can be imagined as a counter of permits that will be decremented when a thread acquires, and incremented when a thread releases. If the amount of permits is 0 when a thr...
A Threadpool has a Queue of tasks, of which each will be executed on one these Threads. The following example shows how to add two int arrays using a Threadpool. Java SE 8 int[] firstArray = { 2, 4, 6, 8 }; int[] secondArray = { 1, 3, 5, 7 }; int[] result = { 0, 0, 0, 0 }; ExecutorService po...
Code snippet: import java.util.Set; public class ThreadStatus { public static void main(String args[]) throws Exception { for (int i = 0; i < 5; i++){ Thread t = new Thread(new MyThread()); t.setName("MyThread:" + i); t.start(); ...
While Runnable provides a means to wrap code to be executed in a different thread, it has a limitation in that it cannot return a result from the execution. The only way to get some return value from the execution of a Runnable is to assign the result to a variable accessible in a scope outside of t...
Prior to Java 5's concurrent package introduction threading was more low level.The introduction of this package provided several higher level concurrent programming aids/constructs. Locks are thread synchronisation mechanisms that essentially serve the same purpose as synchronized blocks or key wor...

Page 1 of 1