How to abort a synchronized method that is locked

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 exit a program, how can I interrupt these pending threads so that the program exits immediately?

I tried calling Thread.interrupt()and Foo.notify()but did not work.

Question: Is the synchronization method lock interrupted?

+4
source share
2 answers

Is synchronous method lock interrupted? 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()
        }
    }
}

, java.util.concurrent.locks.Lock . Java- 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.

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

+3

Source: https://habr.com/ru/post/1548725/


All Articles