Java Concurrency Tutorials
In this detailed Resource page, we feature an abundance of Java Concurrency Tutorials!
The Java programming language and the Java virtual machine (JVM) have been designed to support concurrent programming, and all execution takes place in the context of threads. Objects and resources can be accessed by many separate threads; each thread has its own path of execution but can potentially access any object in the program. The programmer must ensure read and write access to objects is properly coordinated (or “synchronized”) between threads. Thread synchronization ensures that objects are modified by only one thread at a time and that threads are prevented from accessing partially updated objects during modification by another thread. The Java language has built-in constructs to support this coordination.
Most implementations of the Java virtual machine run as a single process and in the Java programming language, concurrent programming is mostly concerned with threads (also called lightweight processes). Multiple processes can only be realized with multiple JVMs.
Threads share the process’s resources, including memory and open files. This makes for efficient, but potentially problematic, communication. Every application has at least one thread called the main thread. The main thread has the ability to create additional threads as Runnable
or Callable
objects. (The Callable
interface is similar to Runnable
, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable
, however, does not return a result and cannot throw a checked exception.)
Each thread can be scheduled on a different CPU core or use time-slicing on a single hardware processor, or time-slicing on many hardware processors. There is no generic solution to how Java threads are mapped to native OS threads. Every JVM implementation can do it in a different way.
Each thread is associated with an instance of the class Thread. Threads can be managed either directly using Thread objects or using abstract mechanisms such as Executor
s and java.util.concurrent
collections.
If you wish to build up your Java Concurrency knowledge first, check out our Multithreading and Concurrency Interview Questions and Answers – The ULTIMATE List.
Java Concurrency Tutorials – Introduction
An introduction on Java Concurrency
- Java Concurrency Essentials Tutorial
In this course, you will dive into the magic of concurrency. You will be introduced to the fundamentals of concurrency and concurrent code and you will learn about concepts like atomicity, synchronization and thread safety. - Introduction to Threads and Concurrency
In the first lesson of our course, you will get introduced to the magical world of Concurrency. You will lean about Threads and how to create them, start them, put them to sleep and more. Additionally, you will get a first look at Synchronization as well as Atomic Access to variables. Sample code is provided for each of the examples. - Concurrency Fundamentals: Deadlocks and Object Monitors
In this lesson, you will learn about important aspects of concurrent applications, such as liveness and multi-threading. You will learn how to avoid common pitfalls of parallel programming, such as deadlocks, thread starvation etc. - The java.util.concurrent Package
In this lesson, we will focus on the java.util.concurrent Package, which includes many interesting classes that provide necessary and helpful functionality needed to implement multi-threaded applications. We will see how to use the relevant API classes, like the executors, the concurrent collections, the atomic variables and more. - Performance, Scalability and Liveness
In this lesson, we discuss the topic of performance for multi-threaded applications. After defining the terms performance and scalability, we take a closer look at Amdahl’s Law. Further in the lesson we see how we can reduce lock contention by applying different techniques, which are demonstrated with code examples. - Fork/Join Framework
In this lesson, we discuss the Fork/Join Framework which is part of the JDK since version 1.7. This framework provides a very handy set of classes that can be used to write concurrent applications based on the relevant algorithm. We will explore the main classes and provide examples on how to use them. - Testing Concurrent Applications
In this final lesson, we will discuss the testing of multi-threaded applications. We implement a simple blocking queue and test its blocking behavior as well as its behavior and performance under stress test conditions. Finally we shed some light on available frameworks for unit testing of multi-threaded classes (e.g. JMock, Grobo Utils, etc).
Java Concurrency Tutorials – Getting Started
Simple examples based on Java Concurrency
- Concurrency best practices
In this part of the tutorial we are going to look at what Java can offer to the developers in order to help them to write robust and safe applications in concurrent world. - CountDownLatch example of a more general wait/notify mechanism
In this example we shall show you how to create a CountDownLatch of a more generalwait/notify
mechanism. We have implemented a method, that istestWaitNotify()
. - Exchanger example passing logs to a background logger
With this example we are going to demonstrate how to create an Exchanger passing logs to a background logger. We have implemented a class,BackgroundLogger
that implements the Runnable interface. - Java 8 Concurrency Tutorial
This article is about concurrency and parallel processing features in Java update 8. It is necessary to mention that concurrency is a very complicated matter and depends strongly in the hardware used for testing and benchmarking. - Java 8 Parallel Arrays Example
In this article we are going to talk about the new possibilities offered in Java 8 for executeArrays
operations in parallel. We are going to focus on theArrays
class methods. - Java CompletionService Example
The Java JDK provides some “services” for common use cases. The asynchronous Producer-Consumer pattern is one such common use case which is often required in day to day software development. - Java CompletionStage and CompletableFuture Example
In this post we would see how CompletionStage and CompletableFuture provide piped asynchronous API thus enhancing reactive programming support in Java at the platform level. - Java ExecutorService Example – Tutorial
In this example we are going to see some basic functionalities ofExecutorService
, as well as handle theFuture
object, the result of asynchronous computation. - Java ReadWriteLock Example
In this example, we are going to demonstrate the use ofReadWriteLock
in Java. - Java Synchronized keyword Example
In this example we shall show you how to use thesynchronized
keyword in Java. Java allows us to use concurrency and multithreading pretty easily. Some of the most common use cases are those in which we have an object and many threads interacting with it. - JavaFX Concurrency Example
This is a JavaFX Concurrency Example. Java GUI applications are inherently multi-threaded. Multiple threads perform different tasks to keep the UI in sync with the user actions. JavaFX, like Swing and AWT, uses a single thread, called JavaFX Application Thread, to process all UI events.
Java Concurrency Tutorials – Functions
Learn the most famous functionalities and operations of Java Concurrency
- Java AtomicInteger Example
This is an example of how to use theAtomicInteger
class of Java. The java.util.concurrent.atomic package provides very useful classes that support lock-free and thread-safe programming on single variables. Among them, theAtomicInteger
class is a wrapper class for anint
value that allows it to be updated atomically. - Java AtomicIntegerArray Example
In this example we shall talk about the AtomicIntegerArray class of Java. Java provides the java.util.concurrent.atomic package specification for lock-free and thread-safe programming on single variables. The AtomicIntegerArray class is anint
array in which elements may be updated atomically. - Java AtomicMarkableReference Example
In this example we shall make use ofAtomicMarkableReference
class of Java. It is another class under thejava.util.concurrent.atomic
package, which provides lock-free and thread-safe programming solutions. - Java AtomicReference Example
This is an example of theAtomicReference
class of Java. It is another class under thejava.util.concurrent.atomic
package, which provides an object reference that may be updated atomically. - java.util.concurrent.atomic.AtomicBoolean Example
In this example, we shall be demonstrating the use ofjava.util.concurrent.atomic.AtomicBoolean
Class added in Java 5. - java.util.concurrent.atomic.AtomicLongArray Example
In this example we shall show you how to make use ofAtomicLongArray
class,AtomicLongArray
is along
array in which elements may be updated atomically. In a multithreading concurrent application architecture, we have a few tasks which are parallelized in such a way as to require no coordination between threads. - Java BlockingQueue Example
In this example we will discuss aboutjava.util.concurrent.BlockingQueue
interface.java.util.concurrent.BlockingQueue
was added in Java 1.5 along with all the other classes and interfaces ofjava.util.concurrent
package. - java.util.concurrent.ArrayBlockingQueue Example
In this post we are going to present theArrayBlockingQueue
class, which implements theBlockingQueue
interface. The main reason to use theArrayBlockingQueue
class is that it is thread-safe, in the sense that it can be used concurrently between different threads without any risk. - java.util.concurrent.ConcurrentHashMap Example
In this post, we are going to discuss about the classjava.util.concurrent.ConcurrentHashMap<K,V>
and give you and idea of how you can use it on your own code when building robust multi-threaded applications. - java.util.concurrent.ConcurrentNavigableMap Example
In this example we shall show you how to make useConcurrentNavigableMap
Interface,ConcurrentNavigableMap
is aNavigableMap
which provides navigation methods that returns the closest match for given search targets with a concurrent access support for its submaps. Thesubmaps
are the maps returned by various methods likeheadMap(K toKey)
,tailMap(K fromKey)
andsubMap(K fromKey, K toKey)
. - java.util.concurrent.ConcurrentSkipListMap Example
ConcurrentSkipListMap
is a scalable concurrent navigable map implementation. The map is sorted based on natural ordering of its keys or by comparator depending on the usage of constructor. - java.util.concurrent.CopyOnWriteArrayList Example
In this post, we are going to discuss about the classjava.util.concurrent.CopyOnWriteArrayList
and give you and idea of how you can use it on your own code when building robust multi-threaded applications. - java.util.concurrent.CopyOnWriteArraySet Example
In this post, we are going to discuss about the classjava.util.concurrent.CopyOnWriteArraySet
and give you and idea of how you can use it on your own code when building robust multi-threaded applications. - Java CountDownLatch Example
In this example we will discuss about the classjava.util.concurrent.CountDownLatch
.java.util.concurrent.CountDownLatch
is a synchronization mechanism that allows one or more threads to wait until a set of operations being performed in other threads completes. - java.util.concurrent.CountDownLatch Example
In this example we will see how and when to usejava.util.concurrent.CountDownLatch
CountDownLatch
is used in synchronisation to allow one or more threads to wait until a set of operations being performed in other threads completes. - Java.util.concurrent.CyclicBarrier Example
In one of the previous posts, we talked aboutCountdownLatch
and its use case. Today we are going to talk about a similar yet different synchronisation mechanism called asCyclicBarrier
. - java.util.concurrent.DelayQueue Example
In this example we shall show you how to make use ofDelayQueue
class.DelayQueue
is an unbounded time-based schedulingBlockingQueue
ofDelayed
elements backed by a heap where an element can only be taken when its delay has expired. - java.util.concurrent.Exchanger Example
In this example, we shall be demonstrating how we can use thejava.util.concurrent.Exchanger
Class in Java. - java.util.concurrent.ForkJoinPool Example
In this example, we shall be demonstrating the use ofjava.util.concurrent.ForkJoinPool
Class. This class was introduced in Java 7. - java.util.concurrent.ForkJoinWorkerThread Example
In this post, we are going to discuss about the classjava.util.concurrent.ForkJoinWorkerThread
and give you and idea of how you can use it on your own code when building robust multi-threaded applications. - java.util.concurrent.FutureTask Example
In this example we shall show you how to makeFutureTask
,FutureTask
is an implementation ofFuture
which offers a very elegant way to implement parallel execution of tasks in Java where a big task can be split into small chunks and if each of those chunks can be executed in parallel, it can result in better response times and throughput. - java.util.concurrent.LinkedBlockingQueue Example
In this example we are going to explain the use of theLinkedBlockingQueue
class, and how it is different from the similarArrayBlockingQueue
. The main point of similarity is the concurrent capabilities of both classes, which makes sense as both are part of thejava.util.concurrent
package. - java.util.concurrent.locks.AbstractQueuedSynchronizer Example
AbstractQueuedSynchronizer
class has support for exclusive and shared mode of locks and synchronizers. It provides methods for inspection, instrumentation and monitoring methods for condition objects. - java.util.concurrent.locks.Condition Example
In this tutorial we will discuss about theCondition
interface in Java. ACondition
object, also known ascondition variable
, provides a thread with the ability to suspend its execution, until the condition is true. ACondition
object is necessarily bound to aLock
and can be obtained using thenewCondition()
method. - java.util.concurrent.Phaser Example
In this example, we shall be demonstrating thejava.util.concurrent.Phaser
Class. The Phaser Class was introduced in Java 7. Phaser is like a collection of advantages ofCountDownLatch
andCyclicBarrier
Classes. - Java ReentrantLock Example
In this example, we shall be demonstrating how to use ReentrantLock in Java. - Java ReentrantReadWriteLock Example
This is an example of how to make use of theReentrantReadWriteLock
class of Java. It is an implementation ofReadWriteLock
, that also supportsReentrantLock
functionality. - Reentrant Lock example of a task runner
With this example we are going to demonstrate how to implement a ReentrantLock of a task runner. The ReentrantLock is a reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed usingsynchronized
methods and statements, but with extended capabilities. - Reentrant ReadWriteLock example of value calculator
This is an example of how to use a ReentrantReadWriteLock of a value calculator. We have implemented a method that uses a ReadWriteLock and implements thecalculate(int value)
, thegetCalculatedValue()
and thegetValue()
methods. - java.util.concurrent.RecursiveTask Example
In this example we shall show you how to make use of JavaRecursiveTask
class,RecursiveTask
provides a convenient way to consolidate results from subtasks. Java 7 introduced another implementation ofExecutorService
: theForkJoinPool
class. - java.util.concurrent.RejectedExecutionHandler Example
Here we will discuss about theRejectedExecutionHandler
Interface in thejava.util.concurrent
package. This interface is really helpfull when working with theThreadPoolExecutor
. - java.util.concurrent.RejectedExecutionException – How to solve RejectedExecutionException
In this example we are going to talk aboutjava.util.concurrent.RejectedExecutionException
. When using anExecutor
to run your threads, it might reach a state where it cannot run the task you asked him to. - Java RunnableFuture Example
In this post, we are going to discuss about the classjava.util.concurrent.RunnableFuture
and give you and idea of how you can use it on your own code when building robust multi-threaded applications. - Java RunnableScheduledFuture Example
In this article we will learn aboutjava.util.concurrent.RunnableScheduledFuture
class which was introduced in Java 6. - java.util.concurrent.ScheduledThreadPoolExecutor Example
In this example, we shall be demonstrating how we can use thejava.util.concurrent.ScheduledThreadPoolExecutor
Class to schedule some periodic Tasks at fixed rate or fixed delay. - Semaphores example limiting URL connections
In this example we shall show you how to use a Semaphore for limiting URL connections. We have implemented a class,ConnectionLimiter
that uses a Semaphore. - java.util.concurrent.Semaphore Example
In this example we shall show you how to make use of use ofjava.util.concurrent.Semaphore
Class in Java. - Java.util.concurrent.SynchronousQueue Example
In this example we will see how to useJava.util.concurrent.SynchronousQueue
.SynchronousQueue
is a type of Blocking Queue (it implementsBlockingQueue
) - Java ScheduledExecutorService Example
In this post we would not just look into these APIs but also compare them against parallel APIsjava.util.TimerTask
andjava.util.Timer
to help us judiciously choose between APIs. - java.util.concurrent.ThreadFactory Example
In this example we shall show you how to make useThreadFactory
interface,ThreadFactory
is implemented by a user class to override itsnewThread()
method for on-demand creation of a new thread with a specific configuration like thread name, type(user
,daemon
) and priority, etc. - java.util.concurrent.ThreadLocalRandom Example
In this example we shall show you how to make use ofThreadLocalRandom
class,ThreadLocalRandom
is a random number generator like its parentRandom
class. Like the globalRandom
generator class, aThreadLocalRandom
is initialized with an internally generated seed that may not otherwise be modified.
[undereg]