Today I Learned: Java Locks

Refresher: Every monitor object has an intrinsic lock, only one thread can acquire it at a given time. A method marked synchronized can only be called by acquiring the intrinsic lock. Let that sync in please (see what I did there, sync lol), as it is important to today’s discussion.

Questions to ask myself: does the current thread have the object in question’s intrinsic lock? If it does, it will execute code in the critical section.

With that refresher out of the way, today we will discuss the lock utility provided to us by Java. Locks are a nifty alternative to the synchronized keyword as they provide us more fine tuned control of the critical section. I’ll explain what I mean by that. Lets look at how to use the lock keyword.

public increment(){
lock.lock();
//critical section
lock.unlock();
}

A key difference between synchronized and lock is that the syncrhonized keyword implementation is reentrant. Let’s look at an example

public synchronized firstMethod(){
   //hi mom
   secondMethod();
}
public synchronized secondMethod(){
   //hi dad
}

The code above will execute smoothly. Synchronized is said to be reentrant. The second method knows that the intrinsic lock is held by the same monitor object and that is it ok to proceed. However, the following will caused us to blocked.

public firstMethod(){
lock.lock();
  //hi mom
  secondMethod();
  lock.unlock();
}
public secondMethod(){
lock.lock();
   //hi dad
  lock.unlock();
}

The problem occurs when we enter the secondMethod. The thread will check to see if the monitor object’s lock is held by the current thread. In this case, it is, and will block until the lock is released. This, of course, does not happen.

With that said, I think the main difference between synchronized and lock lies in reentrance.

Wondering where I learned this stuff? Check out Jakob Jenkov’s series on Java multithreading.

Until tomorrow!

  • J
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.