Understanding High Concurrency in Java: Memory Model, Thread Safety, and Synchronization Techniques
This article explores Java high‑concurrency concepts, detailing the Java Memory Model, thread communication, instruction reordering, atomic classes, synchronization mechanisms, lock implementations, concurrent collections, and safe object publication, providing code examples and practical guidance for building robust multithreaded applications.
The article is organized into three main parts: Java multithreaded programming, high‑concurrency solution strategies, and the use of distributed locks such as Redis and Zookeeper. The focus is on the first part, which explains the Java Memory Model (JMM), thread interaction, and the underlying hardware‑level details that affect concurrency.
It describes how physical CPU, cache, and main memory interact, illustrating the gap in speed that leads to cache coherence protocols (MSI, MESI, etc.). The JMM maps these concepts to Java, defining main memory and working memory for each thread, and explains the eight JMM operations (lock, unlock, read, load, use, assign, store, write) together with their happens‑before rules.
Instruction reordering is covered, distinguishing compiler‑level, parallel‑execution, and memory‑system reorderings, and how the JMM inserts memory barriers to prevent unsafe reorderings.
Testing tools for concurrency are listed (PostMan, Apache Bench, JMeter, LoadRunner) and the three aspects of thread safety—atomicity, visibility, and ordering—are explained with examples.
Key atomic classes are introduced with code examples wrapped in ... tags:
public class AtomicExample1 {
public static int clientTotal = 5000;
public static int threadTotal = 200;
public static AtomicInteger count = new AtomicInteger(0);
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newCachedThreadPool();
Semaphore semaphore = new Semaphore(threadTotal);
CountDownLatch latch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal; i++) {
executor.execute(() -> {
try { semaphore.acquire(); add(); semaphore.release(); }
catch (Exception e) { log.error("exception", e); }
latch.countDown();
});
}
latch.await();
executor.shutdown();
log.info("count:{}", count.get());
}
private static void add() { count.incrementAndGet(); }
}It also shows the internal implementation of AtomicInteger.incrementAndGet() and discusses the ABA problem, loop overhead, and the limitation to a single shared variable.
Other atomic utilities (AtomicLong, LongAdder, AtomicBoolean, AtomicReference, AtomicIntegerFieldUpdater, AtomicStampedReference) are summarized, highlighting their use‑cases and pitfalls.
Thread‑safety strategies are presented: immutable objects, thread confinement (stack, ThreadLocal), avoiding non‑thread‑safe constructs (StringBuilder, SimpleDateFormat, unsynchronized collections), and using synchronized containers (Vector, Hashtable, Collections.synchronizedXXX) when necessary.
Concurrent collections from java.util.concurrent are discussed, including CopyOnWriteArrayList , ConcurrentSkipListSet , ConcurrentHashMap , and their performance characteristics.
The article explains the AbstractQueuedSynchronizer (AQS) framework and how it underpins many synchronizers such as CountDownLatch , Semaphore , CyclicBarrier , ReentrantLock , ReentrantReadWriteLock , and StampedLock . Example snippets for each are provided.
// Example of ReentrantLock usage
final ReentrantLock lock = this.lock;
lock.lock();
try {
// critical section
} finally {
lock.unlock();
}Finally, the article lists thread‑pool types, future tasks, fork/join framework, and various blocking queues (ArrayBlockingQueue, LinkedBlockingQueue, etc.), and points to further reading on Java concurrency best practices.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.