Thread Safety

Leave a comment

May 13, 2010 by huionn

In my opinion, concurrency in Java is one of the hardest skill to master. Looking at the classes in package java.util.concurrent, it is obvious to see how difficult to write correct (thread-safe, no deadlock and optimal performance) classes. For example, in class ThreadPoolExecutor (implementation of Executor), method execute(Runnable) is quite simple in term of LOC, but complex in involved concepts.

public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
            if (runState == RUNNING && workQueue.offer(command)) {
                if (runState != RUNNING || poolSize == 0)
            else if (!addIfUnderMaximumPoolSize(command))
                reject(command); // is shutdown or saturated


Yesterday, I found a issue which is possibly caused by a third party XML parser. The library is not thread safe as a Xerces parser is stored as static variable. Unfortunately, this lib is used in web application which is multithreaded.

As revision, I try to summarize what are characteristics of thread safety from Java Concurrency In Practice.

  1. stateless (simply said, no mutable static or instance variable and the internal state of variable is immutable)
  2. the immutable variable is atomic (such as private final AtomicLong counter = new  AtomicLong(1);) or thread safe (such as ThreadLocal)
  3. all mutable variable access (read/write) are synchronized correctly (for every invariant that involves more than one variable, all the variables involved in that invariant must be guarded by the same lock)
  4. internal states of an object must be confined within the object (in other words, the variables in a thread safe class should not be passed to another object as reference – it is extremely hard to guard the variable outside the scope of original object without compromising liveliness).

In short, if a class has mutable (either w.r.t the reference or its internal state) static / instance variable which is not guarded correctly, it is likely a thread unsafe class.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: