views:

59

answers:

3

Hello! I have a client server application and for testing purposes I need to start the client in a test method by calling

Client.main();

That creates some new thread. Now I need to wait until that thread is completed before performing assertions in my test. How do I know when this happens? Alternatively, how do I know, which thread was started by the call (the client can create other threads too).

+6  A: 

Calling main programmatically won't start a new thread on its own. That would only happen if the main method has code to explicitly start a new thread. If that's the case, you should change Client to provide access to this thread in some form, so you can call join() on it. (Calling Thread.join() is the standard way of waiting for a thread to finish.)

Does Client.main() perform any tasks other than starting a new thread? If not, it would probably be simpler for your tests to just call whatever run() method the new thread will end up running, and making the test single-threaded as far as possible.

Jon Skeet
Thread.getCurrentThread().join();
Suresh S
@Suresh: Um, no. Bad idea.
Jon Skeet
Just to complete the information: Yes, the `Client` is extending `Thread`. And yes, the `main()` does other things too. Anyway, you have been helpful (+1).
Trimack
A: 

You can use join() for waiting for other thread to finish execution.

Dheeraj Joshi
The problem here is: you call `join()` on a thread instance and the OP problem is *getting* those instances.
Andreas_D
A: 

Never tried it but it could work in your special case. Thread has a static metod to get stacktraces for all live threads and with this method you get a Set of thread objects. Calling it before and after calling main should allow you to get references to all threads that have been created/started while the main method executed:

 Set<Thread> before = Thread.getAllStackTraces().keySet();
 Client.main();
 Set<Thread> after = Thread.getAllStackTraces().keySet();

Of course, identifying your threads is even easier (and more reliable) if your threads are created with unique IDs/names. Now you can calculate the difference and call join on all those threads. It may have a hell of sideeffects but, as mentioned above, may help in your specific test case.

Andreas_D
Yeah, I thought of that too. The problem is, there can be created more threads in the main(), so it will most likely not work. Thanks anyway.
Trimack
I thought you wanted to wait for *all* those threads to complete?? So it's just one that you're interested in? Give it name, get the collection of all threads as mentioned above and look for that (named) thread in that collection. join it and you're done.
Andreas_D