whitecoffee
whitecoffee

Reputation: 1045

How to interrupt a synchronized method that is blocked

I have an Object with a synchronized method:

public class Foo {
    public synchronized void bar() {
        // Do stuff
    }
}

And I have thousands of threads calling the same method. When I want to quit the program, how can I interrupt these waiting threads so that the program exits immediately?

I have tried to call Thread.interrupt() and Foo.notify() but not work.

The question is: Is blocking synchronized method interruptible?

Upvotes: 6

Views: 3360

Answers (2)

veritas
veritas

Reputation: 2444

Is blocking synchronized method interruptible? NO ,but below is the best way to achieve what you wanted to do!

public class Foo {
    private final  Lock lock  = new ReentrantLock();
    public void bar() throws InterruptedException {
        lock.lockInterruptibly();
        try {
          // Do stuff
        }finally {
           lock.unlock()
        }
    }
}

Please use java.util.concurrent.locks.Lock for this purpose. From Java doc of lockInterruptibly method

/**
     * Acquires the lock unless the current thread is
     * {@linkplain Thread#interrupt interrupted}.
     *
     * <p>Acquires the lock if it is available and returns immediately.
     *
     * <p>If the lock is not available then the current thread becomes
     * disabled for thread scheduling purposes and lies dormant until
     * one of two things happens:
     *
     * <ul>
     * <li>The lock is acquired by the current thread; or
     * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
     * current thread, and interruption of lock acquisition is supported.
     * </ul>
     *
     * <p>If the current thread:
     * <ul>
     * <li>has its interrupted status set on entry to this method; or
     * <li>is {@linkplain Thread#interrupt interrupted} while acquiring the
     * lock, and interruption of lock acquisition is supported,
     * </ul>
     * then {@link InterruptedException} is thrown and the current thread's
     * interrupted status is cleared.

Reference : http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/locks/ReentrantLock.java#ReentrantLock.lockInterruptibly%28%29

Upvotes: 10

Erica Kane
Erica Kane

Reputation: 3352

You must design the thread to respond properly to an interruption. Unless the thread is checking for one, it won't do anything when interrupt() is called. There is a good explanation here:

http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

Upvotes: 2

Related Questions