kecoliva
kecoliva

Reputation: 80

Is it possible to block/wait an already existing asynchronous function?

SomeLibrary lib = new SomeLibrary();
lib.doSomethingAsync(); // some function from a library I got and what it does is print 1-5 asynchronously
System.out.println("Done");

// output
// Done
// 1
// 2
// 3
// 4
// 5

I want to be clear that I didn't make the doSomethingAsync() function and it's out of my ability to change it. I want to find a way to block this async function and print Done after the numbers 1 to 5 because as you see Done is being instantly printed. Is there a way to do this in Java?

Upvotes: 0

Views: 58

Answers (2)

Nilesh PS
Nilesh PS

Reputation: 366

This is achieved in a couple of ways in standard libraries :-

Completion Callback

Clients can often provider function to be invoked after the async task is complete. This function usually receives some information regarding the work done as it's input.

Future.get()

Async functions return Future for client synchronization. You can read more about them here.

Do check if any of these options are available (perhaps, an overloaded version ?_ in the method you wish to invoke. It is not too uncommon for libraries to include both sync and async version of some business logic so you could search for that too.

Upvotes: 1

Truong Nguyen
Truong Nguyen

Reputation: 449

You can use CountDownLatch as follow:

final CountDownLatch wait = new CountDownLatch(1);
SomeLibrary lib = new SomeLibrary(wait);
lib.doSomethingAsync(); // some function from a library I got and what it does is print 1-5 asynchronously
//NOTE in the doSomethingAsync, you must call wait.countDown() before return
wait.await(); //-> it wait in here until wait.countDown() is called.
System.out.println("Done");

In Constructor SomeLibrary :

private CountDownLatch  wait;
public ScannerTest(CountDownLatch  _wait) {
    this.wait = _wait;
}

In method doSomethingAsync():

public void doSomethingAsync(){
   //TODO something
   ...
   this.wait.countDown();
   return;
}

Upvotes: 1

Related Questions