How do I conditionally lock in Java?

I have been making use of Java’s synchronized blocks to make parts of my code thread safe. I am porting a data structure to java that can usually use synchronized blocks, but I don’t always know how to use them in a typical Java way.

Here is an example of one scenario:

myMethod (Bool useLock)
    {
    if (useLock)
        {
        //locks the following section of code until unlocked.
        lockObject.lock();
        }

     //do more stuff....

    if (useLock)
        {
        //unlocks exclusive control of code.
        lockObject.unlock();
        }
     }

How do I do an equivalent of this in Java? In this code sometimes I want to lock and sometimes I don’t, but I want to be smart about it and not have to write two versions of the same code. Are there other ways of locking in Java other than using synchronized blocks?

Answer

You can use Lock objects, ReentrantLock in particular should do the work. http://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html

Or you can still solve the issue with synchronized blocks. The code from your question will look like:

myMethod (Bool useLock) {
    if (useLock) {
        synchronized (this) {
           criticalSection();
        }
    } else {
        criticalSection();
    }
}

criticalSection() {
   //do more stuff....
}

Or if you want to guarantee the mutual exclusion among different instances of the class you should use other monitor object than this. For instance TheClassName.class or other explicitly defined static variable of that class.

Leave a Reply

Your email address will not be published. Required fields are marked *