Home » Java Concurrency Tutorials

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 Executors and java.util.concurrent collections.

Note
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 general wait/notify mechanism. We have implemented a method, that is testWaitNotify().
  • 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 execute Arrays operations in parallel. We are going to focus on the Arrays 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 of ExecutorService, as well as handle the Future object, the result of asynchronous computation.
  • Java ReadWriteLock Example
    In this example, we are going to demonstrate the use of ReadWriteLock in Java.
  • Java Synchronized keyword Example
    In this example we shall show you how to use the synchronized 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 the AtomicInteger 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, the AtomicInteger class is a wrapper class for an int 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 an int array in which elements may be updated atomically.
  • Java AtomicMarkableReference Example
    In this example we shall make use of AtomicMarkableReference class of Java. It is another class under the java.util.concurrent.atomic package, which provides lock-free and thread-safe programming solutions.
  • Java AtomicReference Example
    This is an example of the AtomicReference class of Java. It is another class under the java.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 of java.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 of AtomicLongArray class,  AtomicLongArray is a long 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 about java.util.concurrent.BlockingQueue interface. java.util.concurrent.BlockingQueue was added in Java 1.5 along with all the other classes and interfaces of java.util.concurrent package.
  • java.util.concurrent.ArrayBlockingQueue Example
    In this post we are going to present the ArrayBlockingQueue class, which implements the BlockingQueue interface. The main reason to use the ArrayBlockingQueue 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 class java.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 use ConcurrentNavigableMap Interface, ConcurrentNavigableMap is a NavigableMap which provides navigation methods that returns the closest match for given search targets with a concurrent access support for its submaps. The submaps are the maps returned by various methods like headMap(K toKey), tailMap(K fromKey) and subMap(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 class java.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 class java.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 class java.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 use java.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 about CountdownLatch and its use case. Today we are going to talk about a similar yet different synchronisation mechanism called as CyclicBarrier.
  • java.util.concurrent.DelayQueue Example
    In this example we shall show you how to make use of DelayQueue class. DelayQueue is an unbounded time-based scheduling BlockingQueue of Delayed 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 the java.util.concurrent.Exchanger Class in Java.
  • java.util.concurrent.ForkJoinPool Example
    In this example, we shall be demonstrating the use of java.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 class java.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 make FutureTaskFutureTask is an implementation of Future 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 the LinkedBlockingQueue class, and how it is different from the similar ArrayBlockingQueue. The main point of similarity is the concurrent capabilities of both classes, which makes sense as both are part of the java.util.concurrent package.
  • java.util.concurrent.locks.AbstractQueuedSynchronizer ExampleAbstractQueuedSynchronizer 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 the Condition interface in Java. A Condition object, also known as condition variable, provides a thread with the ability to suspend its execution, until the condition is true. A Condition object is necessarily bound to a Lock and can be obtained using the newCondition() method.
  • java.util.concurrent.Phaser Example
    In this example, we shall be demonstrating the java.util.concurrent.Phaser Class. The Phaser Class was introduced in Java 7. Phaser is like a collection of advantages of CountDownLatch and CyclicBarrier 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 the ReentrantReadWriteLock class of Java. It is an implementation of ReadWriteLock, that also supports ReentrantLock 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 using synchronized 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 the calculate(int value), the getCalculatedValue() and the getValue() methods.
  • java.util.concurrent.RecursiveTask Example
    In this example we shall show you how to make use of Java RecursiveTask class, RecursiveTask provides a convenient way to consolidate results from subtasks. Java 7 introduced another implementation of ExecutorService: the ForkJoinPool class.
  • java.util.concurrent.RejectedExecutionHandler Example
    Here we will discuss about the RejectedExecutionHandler Interface in the java.util.concurrent package. This interface is really helpfull when working with the ThreadPoolExecutor.
  • java.util.concurrent.RejectedExecutionException – How to solve RejectedExecutionException
    In this example we are going to talk about java.util.concurrent.RejectedExecutionException. When using an Executor 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 class java.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 about java.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 the java.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 of java.util.concurrent.Semaphore Class in Java.
  • Java.util.concurrent.SynchronousQueue Example
    In this example we will see how to use Java.util.concurrent.SynchronousQueue. SynchronousQueue is a type of Blocking Queue (it implements BlockingQueue)
  • Java ScheduledExecutorService Example
    In this post we would not just look into these APIs but also compare them against parallel APIs java.util.TimerTask and java.util.Timer to help us judiciously choose between APIs.
  • java.util.concurrent.ThreadFactory Example
    In this example we shall show you how to make use ThreadFactory interface, ThreadFactory is implemented by a user class to override its newThread() 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 of ThreadLocalRandom class, ThreadLocalRandom is a random number generator like its parent Random class. Like the global Random generator class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified.
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy