ConditionRacer
ConditionRacer

Reputation: 4498

How to create a method that accepts a callback function in java?

I created a distributed lock class that I designed to be used like this:

myLock.lock();
doSomething();
myLock.unlock();

In my current implementation, lock() blocks until the lock is acquired. But I am running into some deadlock issues with this implementation. So I'd like to rewrite it to be asynchronous, but I have no idea how to do that in java.

Something like this would work I think:

myLock.lock(myCallbackFunction);

private void myCallbackFunction(boolean result){
    if(result){
        doSomething();
        mylock.Unlock();
    }
}

Is there a way to do this in java?

EDIT (More detail): The reasons why the synchronous implementation is deadlocking are complicated and not relevant. The distributed lock is acquiring mutual exclusion of a resource across a network with multiple systems. Really the only thing I'm looking for is how to write a method that accepts a callback function.

Upvotes: 0

Views: 247

Answers (2)

jacobm
jacobm

Reputation: 14025

You can't do that in Java yet. What you can do is define a LockCallback interface:

interface LockCallback {
  void run(boolean result, MyLock lock);
}

and have MyLock#lock take a LockCallback as a parameter. Then callers can call it as

myLock.lock(new LockCallback {
  public void run(boolean result, MyLock lock) {
    // ... do whatever needs to be done ...
    lock.unlock();
  });

Lambda syntax in Java 8 should make this a little less ugly looking.

Upvotes: 3

Ryan Stewart
Ryan Stewart

Reputation: 128799

Instead of writing your own and then abandoning the idea because you couldn't make it work, why not use a Semaphore, which is already there and is implemented correctly?

Upvotes: 0

Related Questions