Backend Development 38 min read

Understanding Java Concurrency: Synchronized Containers, OS Concurrency Tools, and Java Concurrency Utilities

This article provides a comprehensive overview of Java concurrency, covering synchronized container classes, operating‑system level synchronization primitives, and the rich set of concurrent utilities introduced in the Java standard library, with code examples and explanations of fail‑fast and fail‑safe mechanisms.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Understanding Java Concurrency: Synchronized Containers, OS Concurrency Tools, and Java Concurrency Utilities

The article introduces the organization of Java concurrency topics, starting with synchronized container classes such as Vector , Hashtable , and Stack , which use the synchronized keyword for thread safety, and the Collections.synchronizedXXX wrappers like Collections.synchronizedList and Collections.synchronizedMap .

同步容器类

Although these containers are thread‑safe, complex composite operations (e.g., "check‑then‑act") often require additional client‑side locking to guarantee atomicity, illustrated with a if (a == null) { a = get(); } example and a full TestVector class that demonstrates race conditions leading to ArrayIndexOutOfBoundsException .

if(a == null){
  a = get();
}
public class TestVector implements Runnable {
    static Vector vector = new Vector();
    static void addVector(){
        for(int i=0;i<10000;i++){
            vector.add(i);
        }
    }
    static Object getVector(){
        int index = vector.size() - 1;
        return vector.get(index);
    }
    static void removeVector(){
        int index = vector.size() - 1;
        vector.remove(index);
    }
    @Override
    public void run(){
        getVector();
    }
    public static void main(String[] args){
        TestVector testVector = new TestVector();
        testVector.addVector();
        Thread t1 = new Thread(() -> {
            for(int i=0;i
{
            for(int i=0;i

To avoid such issues, the article recommends client‑side locking using synchronized blocks on the container object or its class, ensuring atomicity of composite operations.

fail‑fast

Many collection classes implement a fail‑fast mechanism that throws ConcurrentModificationException when a collection is modified during iteration, providing a "good‑will" detection of concurrent errors.

fail‑safe

Fail‑safe collections, such as CopyOnWriteArrayList and the classes in java.util.concurrent , work on a snapshot of the data, allowing safe iteration without exceptions even when concurrent modifications occur.

操作系统中的并发工具

The article then surveys OS‑level concurrency primitives: semaphores (down/up), mutexes (locked/unlocked), futexes (fast user‑space mutexes), and monitors, explaining their semantics and typical usage patterns.

信号量 (Semaphore)

A counting semaphore maintains a set of permits; acquire blocks when no permits are available, and release returns a permit.

互斥量 (Mutex)

Mutexes provide exclusive access to critical sections, with lock and unlock operations; POSIX pthreads expose pthread_mutex_lock , pthread_mutex_unlock , etc.

条件变量 (Condition Variable)

Condition variables allow threads to wait for a predicate to become true, using pthread_cond_wait and pthread_cond_signal / pthread_cond_broadcast .

管程 (Monitor)

Monitors combine mutexes and condition variables into a language‑level construct, ensuring only one active process inside the monitor at a time.

Java 并发工具包

Java 5 introduced a rich set of concurrent utilities: ConcurrentHashMap (with segment locks for high throughput), CopyOnWriteArrayList , BlockingQueue variants (e.g., LinkedBlockingQueue , ArrayBlockingQueue , PriorityBlockingQueue ), ConcurrentSkipListMap / Set , Semaphore , CountDownLatch , Future / FutureTask , Barrier (CyclicBarrier), Exchanger , and others.

ConcurrentHashMap

Uses segment locking to allow concurrent reads and writes, offering weak consistency (no ConcurrentModificationException ) and higher throughput than Hashtable or Collections.synchronizedMap .

ConcurrentMap Interface

public interface ConcurrentMap
extends Map
{
    V putIfAbsent(K key, V value);
    boolean remove(Object key, Object value);
    V replace(K key, V value);
    boolean replace(K key, V oldValue, V newValue);
}

BlockingQueue

Supports four usage modes (exception, special value, blocking, timeout) and is essential for producer‑consumer patterns. Implementations include LinkedBlockingQueue , ArrayBlockingQueue , PriorityBlockingQueue , SynchronousQueue , etc.

Semaphore

Controls the number of concurrent accesses to a resource, useful for connection pools and rate limiting.

CountDownLatch

Allows one or more threads to wait until a set of operations completes, using await and countDown .

Future & FutureTask

Represent asynchronous computation results; Future.get() blocks until the result is ready. FutureTask implements RunnableFuture , enabling submission to executors.

Barrier (CyclicBarrier)

Blocks a group of threads until all have reached the barrier, then optionally runs a barrier action.

Exchanger

Pairs threads to exchange data at a synchronization point via exchange() .

总结

The article ties together synchronized containers, fail‑fast/fail‑safe mechanisms, OS‑level synchronization primitives, and the extensive Java concurrency utilities, emphasizing when to use each tool to achieve thread safety and high performance.

JavaconcurrencyThreadSafetyConcurrentUtilitiesSynchronizedContainers
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.