Java – Implementing a global lock in Java

globaljavalockingmultithreading

I have a relatively simple (perhaps stupid) question regarding synchronisation in Java.

I have synchronisation blocks that acquire locks on various objects throughout my code. In some scenarios, I want to acquire a global lock that subsumes every other synchronisation statement in my code.

Is there a fancy way to do this in Java without re-writing all the current synchronisation code?

For example,

Thread t1

synchronized (o1)
{
    synchronized (o2)
    {
        // ...
    }
}

Thread t2

synchronized (global_lock)
{
    // ...
}

When thread t2 is inside the synchronised block, thread t1 should not be allowed to acquire the locks on o1 and o2.

Many thanks
if

Best Solution

  1. It's not possible;
  2. It's a really bad idea ( sorry ).

It's deadlock-prone, since it forces you to have a pre-determined locking order for all locks, no matter where they are.

Usually it's a good idea, if you need to acquire two locks, to always have a predetermined order:

synchronized(LOCK1) {
  synchronized(LOCK2) {

  }
}

But a global lock would need some sort of protocol - a global aquisition order - for all the locks. And that may not be possible at all. Most locks guard specific, self-contained, critical sections. They would be unaware that someone would 'yank' them out and aquire them and therefore would not be written to handle this situation.

So it's not possible, and you should be happy it's not. Although it seems to be the easy way out, it would bring a lot of pain.