0

I want to make sure the the main thread is blocked until an asynchronous call is finished. I am creating a new Thread to execute the async code. here is my code:

Thread r = new Thread() {
    public void run() {
    asyncCall();
    }
};
r.run();
r.join();

r.join will block the main thread until r dies. is that sufficient? when the thread r actually dies? is it after the async call is done.

Soof
  • 73
  • 9
  • What's the point in creating a Thread then? Does the "asyncCall" call back to indicate completion? – Fildor Jan 18 '16 at 13:20
  • NB: `r.run()` is the wrong way to invoke a thread's function. You need to use `r.start()`. – OldCurmudgeon Jan 18 '16 at 13:24
  • Is `asyncCall` part of some 3rd party API? – Fildor Jan 18 '16 at 13:24
  • Can you tell us what Framework it is? I guess you'll have to listen on some callback. But we won't know if we don't know the API. Wrapping the starting call will not help if the library starts yet another thread for task execution. You'll end up waiting for the enqueing to finish, not the whole transaction. – Fildor Jan 18 '16 at 15:03

2 Answers2

2

First of all, you need to call thread.start() and not thread.run(), and the answer is yes, thread.join blocks until the thread dies.

When does it actually die? Check this out

It is recommended however to use an executor and not Threads directly.

Future<?> future =  executor.submit(()->{});
future.get(); // blocks here
Community
  • 1
  • 1
Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
1

r.join will block the main thread until r dies.

Correct.

is that sufficient?

if the goal is to prevent main thread from continuing execution while r is running ayncCall then yes.

when the thread r actually dies? is it after the async call is done.

you can say that the thread finishes execution after asyncCall is done. "dying" depends on you definition. the thread may be alive after asyncCall is done because the JVM dedcided to re-use it for other purpose. it may not.

ps. you need to call Thread.start() , not Thread.run().

David Haim
  • 25,446
  • 3
  • 44
  • 78
  • thanks for your clear answer. assuming that the async call is an async update to a database. does my piece of code insure that the update is done before the program continues execution? – Soof Jan 18 '16 at 13:13
  • 1
    yes, although, if there is nothing between the `Thread.start()` and `Thread.join()` you might as well not create a thread in the first place but just put the function as part of main. – David Haim Jan 18 '16 at 13:15