RSS feed [root] /concurrency /weblog /java



title search:


Sat Mar 09 23:33:22 HKT 2019


(google search) (amazon search)
download zip of files only

Sat Mar 09 23:33:41 HKT 2019 From /weblog/java/concurrency


(google search) (amazon search)

Sun Feb 17 01:15:24 HKT 2019 From /weblog/java/concurrency


Another nice tutorial set of concurrency framework -

Java concurrency, Building and testing concurrent applications for the Java platform -[..]/training/kp/j-kp-concurrency/index.html

JVM concurrency: Java and Scala concurrency basics -[..]/java/library/j-jvmc1/index.html?ca=drs-[..]reading-interview-questions-answers.html

5 things you didn't know about ... Multithreaded Java programming -

266Threading Questions in Job Interviews (2/2) -

(google search) (amazon search)

Thu Sep 28 16:21:47 HKT 2017 From /weblog/java/concurrency


preventing false sharing with the @Contended annotation -[..]false-sharing-is-and-how-jvm-prevents-it

(google search) (amazon search)

Fri Mar 10 17:49:16 HKT 2017 From /weblog/java/concurrency


putall can cause ConcurrentModifcationException -[..]ses/sun/management/

Note on writing CopyOnWrite wrapper -[..]

Sometime this is a bit difficult for Chinese to be a good programmer, recently some colleague and me discuss about the behaviour of this class and look like we have difficult understanding

A: ConcurrentHashMap support for locking as this is thread-safe
B: ConcurrentHashMap is thread safe for read but not for write because there is no lock, we still need to have external lock to keep it thread safe. By the way, I get ConcurrentModificationException from this before.
C: ConcurrentHashMap don't support for locking but they still thread safe for all operations, which is how "This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details." mentioned.

Too good that we can actually take a look at the source code to see what going on nowadays rather than just guessing -[..]HashMap&sourceid=opera&ie=utf-8&oe=utf-8 By the way, this constructor is useful for a lot of concurrency access but actually not many developer notice about this -[..]rrentHashMap.html#ConcurrentHashMap(int, float, int)

Lazy initialization of map values -[..]

HashMap.get() can cause infinite loop -[..]5/07/hashmapget_can_cause_an_infini.html

Discussing the effect of initCapacity() of HashMap in Java -[..]ltimatebb.cgi?ubb=get_topic&f=1&t=021171

OpenJDK and HashMap …. Safely Teaching an Old Dog New (Off-Heap!) Tricks -

We can run search in ConcurrenctHashMap -

(google search) (amazon search)

Tue Jan 03 09:45:40 HKT 2017 From /weblog/java/concurrency


Similar to Barrier -

An example, show how to coordinate producer and consumer with Phaser -[..]08/java-7s-jucphaser-short-tutorial.html

When to use CountDownLatch, Semaphore, CyclicBarrier, Exchanger and Phaser -

(google search) (amazon search)

Thu Oct 06 23:58:24 HKT 2016 From /weblog/java/concurrency


ReentrantReadWriteLock -[..]loperworks/library/j-jtp10264/index.html

why it suppose to be faster than VM level lock -[..]sr.166-concurrency/2005-02/msg00031.html and a test about it -[..]r/2011/11/java-lock-implementations.html

Samples of how to use it, and how to write test cases about it -

Some useful VM parameter to tune the locks: -XX:+EliminateLocks , -XX:+DoEscapeAnalysis , -XX:+UseBiasedLocking -[..]locking-escape-analysis-for-dummies.html

Discuss about 3 difference lock for Java, bias, thin and fat -

Why using the read lock will make lock detector fail -[..]concurrency-hidden-thread-deadlocks.html

Basic of synchronization and locking -[..]about-synchronization-in-java-and-scala/

Better semaphore with striped api -

Comparing and discuss difference locking approach -

Compare performance behavior of RWLock, StampedLock and Optimistic lock -[..]ocks-vs-readwritelocks-and-synchronized/

Comparing sync and lock -[..]ase-study-in-analysing-latency-lock.html

(google search) (amazon search)

Tue Jul 05 16:29:21 HKT 2016 From /weblog/java/concurrency


(google search) (amazon search)

Thu Feb 11 15:53:45 HKT 2016 From /weblog/java/concurrency


Just know that interrupt() call is just setting a flag, it have to be doing IO work (like database call), or in wait() status, before the thread can really be interrupted.[..]winger?entry=swingworker_stop_that_train

Another nice explanation about interrupt, in summary:

What should we do when we call code that may cause an InterruptedException? Don't immediately yank out the batteries! Typically there are two answers to that question:
1) Rethrow the InterruptedException from your method. This is usually the easiest and best approach. It is used by the new java.util.concurrent.* package [[..]util/concurrent/Semaphore.html#acquire() ], which explains why we are now constantly coming into contact with this exception.
2) Catch it, set interrupted status, return. If you are running in a loop that calls code which may cause the exception, you should set the status back to being interrupted. For example:
while (!Thread.currentThread().isInterrupted()) {
// do something
try {
} catch (InterruptedException e) {
Remember the Law of the Sabotaged Doorbell - don't just ignore interruptions, manage them properly!


Another blog explain about InterruptedException -[..]terruptedexception-and-interrupting.html[..]running-infinite-java-regular-expression[..]derstanding-thread-interruption-in-java/

(google search) (amazon search)

Wed Apr 02 11:53:54 HKT 2014 From /weblog/java/concurrency


Even though

private List synchList = Collections.synchronizedList(new LinkedList());

is thread safe, serialize sync List is NOT thread safe for sure. The story is, if you only synchronized the collection, and if we try to get the iterator in concurrent access environment, it will throws currencymodificationexception .

For collection is small, may be making defensive copy is good. Otherwise, in java5, there is concurrency collection.


Map operation, include use of FutureTask and putIfAbsent() method from ConcurrentMap. -

Other then lterate through the elements, adding and removing elements can also be problem, this article document a few good cases about that -[..]en-a-synchronized-class-isnt-threadsafe/

Samples of using Queue.drainTo() -[..]rforming-fixed-amounts-of-work-with.html

Overview of blockingqueue -[..]/java-util-concurrent/blockingqueue.html

Simple benchmark -[..]jvm-performance-part-iii-concurrent.html

Multi-thread behaviour -[..]hread-safety-issues-with-vector-and.html

java.util.concurrent.ConcurrentHashMap VS openhft.collections.SharedHashMap -[..]autilconcurrentconcurrenthashmap-vs.html

(google search) (amazon search)

Wed Mar 26 11:10:08 HKT 2014 From /weblog/java/concurrency


How weak and soft reference work[..]rence-phantom-strong-reference-java.html

Issue about weakhashmap -

When soft reference clean? -[..]/07/how-hotspot-decides-to-clear_07.html

(google search) (amazon search)

Wed Jan 08 17:44:21 HKT 2014 From /weblog/java/concurrency


An API to get the state of a thread, but someone say it is not reliable -[..]5.0/docs/api/java/lang/Thread.State.html[..]readed-programs-tf3627394.html#a10128844

Having said that, I have to note that using Thread#getState() is not
something you can absolutely rely on as the behavior isn't guaranteed
to be the same on all platforms. That is, it can be a useful tool for
debugging and test-driving but not ideal for regression (unit)

Overview of Java thread -[..]t-thread-and-javalangthread-in-java.html

(google search) (amazon search)

Mon Dec 23 18:09:08 HKT 2013 From /weblog/java/concurrency


Demo how java 1.5 built-in thread pool work:[..]ry=swingworker_throttling_and_monitoring

Sample of thread pool -

Discussion about how to estimate threadpool size -

(google search) (amazon search)

Thu Nov 07 16:02:21 HKT 2013 From /weblog/java/concurrency


There is a little bit performance cost for threadlocal variable -[..]ost-of-accessing-thread-local-variables/

Look like a useful but less known API -

Forward up discussion -[..]d_id=41473&asrc=EM_NNL_406677&uid=703565 pointing out some problems of using this technique, include similar effect of GLOBLE , possible memory leak

Another discussion in higher level -[..]04/thread-local-a-convenient-abomination , Key is "An object is an abstraction of function. A thread is an abstraction of schedule" , you can read further conclusion at

Protential issue of using threadlocal, one is memory leak and the other is it is that local -[..]hreading-stories-threadlocal-in-web.html[..]shoot-yourself-in-foot-with-threadlocals

The beauty of the design of threadlocal, how it prevent locking and memory leaking -

(google search) (amazon search)

Thu Oct 31 18:07:36 HKT 2013 From /weblog/java/concurrency


Benchmark for LongAddr -[..]

If there is a concern about wasting too many memory for Atomic* wrapper class, we may consider changed to use AtomicFieldUpdater to update primitive directly -[..]/Lesser-known-concurrent-classes-Part-1/

(google search) (amazon search)

Tue Oct 22 17:25:00 HKT 2013 From /weblog/java/concurrency

Double-Checked Locking

Very detailed explanation:[..]va/memoryModel/DoubleCheckedLocking.html

Some more information, also demo in fact not much difference for most cast:[..]page/cwebster?entry=double_check_locking

Even more discussion -

In Chinese -[..]hecked-locking-with-delay-initialization

(google search) (amazon search)

Mon Sep 23 18:11:40 HKT 2013 From /weblog/java/concurrency


Series of blog showing how to use JMock API to help testing MT code -[..]shhtresohqc&ie=UTF-8&q=JMock+and+Threads

A test for deadlock -[..][..]t/java/util/logging/

Some technique, use of SynchronousExecutorService and Events -[..]ntent/5-tips-unit-testing-threaded-code/

(google search) (amazon search)

Wed Aug 14 02:15:36 HKT 2013 From /weblog/java/concurrency


Sample ResubmittingScheduledThreadPoolExecutor, the coding is nice!

Implement thread pool properly -

RetryExecutor -[..]/2013/07/asynchronous-retry-pattern.html

(google search) (amazon search)

Fri Jun 08 00:56:58 HKT 2012 From /weblog/java/concurrency


Collections from IBM -[..]rworks/training/kp/j-kp-actorconcurrency

(google search) (amazon search)

Sun Nov 13 02:37:44 HKT 2011 From /weblog/java/concurrency


Example of Join -

(google search) (amazon search)

Sun Sep 25 09:35:12 HKT 2011 From /weblog/java/concurrency


Yield is not that reliable-[..]-pair-of-somebody-elses-concurrency-bugs

(google search) (amazon search)

Sun Aug 28 19:58:48 HKT 2011 From /weblog/java/concurrency


Sample code of try-sync

import sun.misc.*;

import java.lang.reflect.*;

public class MonitorUtils {
private static Unsafe unsafe = getUnsafe();

public static boolean trySynchronize(Object monitor) {
return unsafe.tryMonitorEnter(monitor);

public static void unsynchronize(Object monitor) {

private static Unsafe getUnsafe() {
try {
for (Field field : Unsafe.class.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers())) {
if (field.getType() == Unsafe.class) {
return (Unsafe) field.get(null);
throw new IllegalStateException("Unsafe field not found");
} catch (Exception e) {
throw new IllegalStateException(
"Could not initialize unsafe", e);

(google search) (amazon search)

Mon Jun 27 00:27:08 HKT 2011 From /weblog/java/concurrency


A nice list of hints about concurrency in java -[..]c_burke_java_concurrency_by_example.html

Testing about java parallel processing -[..]ng-and-multi-core-utilization-with-java/

Some concurrency basic information -

Tutorial of concurrency package -

Using Latch with Executor -[..]06/new-shimmer-for-java-concurrency.html

(google search) (amazon search)

Wed Feb 16 01:16:05 HKT 2011 From /weblog/java/concurrency


Here is an tricky concurrency concern in Java when using Anonymous Inner Class with ExecutorService, if you use collection from outside class, that collection actually a global variable in the Inner Class, and need to take care the issues happened in concurrency access.

For this class:

public static void main(String[] args) throws InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(80);
final List list = new ArrayList();
for (int i = 0; i < 100000; i++)
es.execute(new Runnable() {
public void run() {
list.add(new String());
while (true) {
boolean terminated = es.awaitTermination(5, TimeUnit.SECONDS);
if (terminated) {
for (String string : list) {
if (string == null)
System.out.println("Have null");

actually same as

private static final class RunnableImpl implements Runnable {
private final List mList;
private RunnableImpl(List list) {
mList = list;

public void run() {
mList.add(new String());
public static void main(String[] args) throws InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(80);
final List list = new ArrayList();
for (int i = 0; i < 100000; i++)
es.execute(new RunnableImpl(list));
/** @formatter:on */
while (true) {
boolean terminated = es.awaitTermination(5, TimeUnit.SECONDS);
if (terminated) {
for (String string : list) {
if (string == null)
System.out.println("Have null");

(google search) (amazon search)