views:

362

answers:

3

Hi,

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

+11  A: 
  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.

Robert Munteanu
A: 

The only feasible way to do it would be actually parse/modify/save (automatically) all the code. I did something like this for a project recently and it worked pretty good. We can talk more if you are interested.

Toader Mihai Claudiu
A: 

Leaving aside the sheer horror of what you are proposing, you may want to consider using Aspect Oriented Programming (AOP) to "weave" additional synchronization/locking into your code at run time. You should be able to do this without writing the source.

There are many AOP options, including AspectJ and Spring AOP, which may be suitable depending on your environment.

skaffman