Transfer a lock to a spawned thread in Java
Is there a way to do something like this in Java (possibly using Lock
instead of synchronized
):
synchronized(lock) {
Thread t = spawnThread(new Runnable() {
synchronized(lock) {
doThing();
}
});
transferLockOwnership(lock, t);
}
Specifically, I'd like to replace code like this:
synchronized (lock) {开发者_运维问答
sendResponse(response);
doThingsAfterSending();
}
With something like this:
synchronized (lock) {
Thread t = spawnThread(new Runnable() { @Override public void run() {
synchronized(lock) { doThingsAfterSending(); }
}});
transferLockOwnership(lock, t);
return response;
}
Have you considered using a Semaphore
with 1 permit? E.g.
private Semaphore lock= new Semaphore(1);
// Instead of synchronized(lock)
lock.acquireUninterruptibly();
Thread t = spawnThread(new Runnable() {
@Override public void run() {
try {
// Do stuff.
} finally {
lock.release();
}
}
});
t.start();
No, you can't. A Lock
and a monitor as used by synchronized
can only be held by a single thread. And "moving" it to another requires releasing the lock and re-acquiring, which includes the danger of another thread getting it instead of the desired one.
If you need something like this, you'll have to build it yourself from the basic blocks: producer your own Lock
-like class that uses Lock
to be thread-safe, but which provides a transferToThread()
method.
精彩评论