0

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.

4
  • 3
    "So I'd like to rewrite it to be asynchronous" - A lock is synchronous by definition. What do you mean by "I'd like to rewrite it to be asynchronous"? Commented Mar 4, 2013 at 2:56
  • Have you seen this? Commented Mar 4, 2013 at 2:57
  • You should provide more details about these methods. When exactly are you getting the deadlock? Commented Mar 4, 2013 at 2:58
  • You need to start a thread, or use one of the thread pool facilities. Commented Mar 4, 2013 at 3:07

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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?

2 Comments

Still doesn't make anything asynchronous.
@HotLicks: True, but while the question's title is about asynchronous methods, that's not what the content of the question talks about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.