Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I interrupt a synchronized statement in Java?

I have two threads that want to synchonize on the same object. Thead A needs to be able to interrupt Thread B if a certain condition has been fullfilled. Here is some pseudo-code of what the two threads do/should do.

A:

public void run()
{
    while(true)
    {
        //Do stuff
        synchronized(shared)
        {
            //Do more stuff
            if(condition)
            {
                B.interrupt();
            }
        }
    }
}

B:

public void run()
{
    while(true)
    {
        try
        {
            //Do stuff
            synchronized(shared)
            {
            //Do more stuff
            }
        }
        catch(InterruptedException e)
        {
            continue;
        }
    }
}

Here's the situation I can't resolve:

  • Thread A grabs the shared resource and does some stuff.
  • Meanwhile, Thread B reaches the synchronized block, and awaits for A to release its shared resource.
  • Thread A, while doing stuff, realized that Thread B should not have the shared resource, and tries to interrupt Thread B. But Thread B has already surpassed the points where an InterruptedException could be thrown.

My question is, is there any way to interrupt a thread while it is waiting to be synchronized on something?

like image 288
Eric Avatar asked Feb 21 '10 13:02

Eric


1 Answers

For this kind of thing, you should use the classes in java.util.concurrent.locks - they have far more capabilities, including interruptable locks.

Edit: If you cannot use those classes, then look at jkff's answer - your requirements can be met with the wait()/notify() mechnism, but it's easy to introduce subtle bugs.

like image 164
Michael Borgwardt Avatar answered Oct 18 '22 04:10

Michael Borgwardt