Bart van Heukelom
Bart van Heukelom

Reputation: 44104

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;

    }

Upvotes: 2

Views: 398

Answers (2)

user545680
user545680

Reputation:

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();

Upvotes: 5

Joachim Sauer
Joachim Sauer

Reputation: 308061

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.

Upvotes: 3

Related Questions