Reputation: 576
I have a ServerState
object:
public class ServerState {
public static final LOCK = new ReentrantLock();
public static Map<String, Object> states = new HashMap<>();
}
Thread A:
public class ThreadA extends Thread {
@Override
public void run() {
ServerState.LOCK.lock();
// do some dirty work
ServerState.LOCK.unlock();
}
}
My question is: when thread A has acquired the lock and is doing some dirty work, thread B wants to terminate A immediately but want it release the lock before its terminate, how can I achieve this? I am not looking for use a flag to indicate whether the thread is terminated like this:
public class ThreadA extends Thread {
volatile boolean isFinished = false;
@Override
public void run() {
while (!isFinished) {
ServerState.LOCK.lock();
// do some dirty work
ServerState.LOCK.unlock();
}
}
What I want to achieve is to terminate the thread and release the lock WITHOUT proceeding to the next iteration. Is is possible to do it in Java?
Upvotes: 0
Views: 1578
Reputation: 8341
You can use thread interruption mechanism.
If you want to interrupt on LOCK
acquiring, you should use LOCK.lockInterruptibly()
instead of LOCK.lock()
:
Thread thread1 = new Thread() {
@Override
void run() {
try {
LOCK.lockInterruptibly();
System.out.println("work");
LOCK.unlock();
} catch (InterruptedException ier) {
this.interrupt()
}
}
};
Then, to stop thread1
just call
thread1.interrupt();
from another thread.
Also I'd suggest to move actual logic from Thread
to Runnable
:
Thread thread1 = new Thread(
new Runnable() {
@Override
void run() {
try {
LOCK.lockInterruptibly();
System.out.println("work");
LOCK.unlock();
} catch (InterruptedException ier) {
Thread.currentThread().interrupt()
}
}
}
);
Upvotes: 1