Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method on thread termination

I am writing a java program which tracks as threads are created in a program and is then supposed to perform some work as each Thread terminates.

I dont see any 'thread termination hooks' out there in the javadoc.

Currently the only way I can think of to achieve my requirement is to hold on to the thread objects and query its 'state' at repeated intervals.

Is there any better way to do this?

Edit: I cannot wrap the runnable or modify the runnable in any way. My code uses runtime instrumentation and just detects that a thread is created and gets a reference to the Thread object. The runnable is already running at this point.

like image 606
pdeva Avatar asked Dec 09 '22 21:12

pdeva


2 Answers

You can use the join() method.

EDIT

If your main thread must not be blocked until threads are not terminated, you can create a sub main thread which will call the threads, then wait for them with join() method.

like image 192
Jérôme Avatar answered Dec 27 '22 06:12

Jérôme


I see four possible methods.

  1. Use your own Thread subclass with an overridden run() method. Add a finally block for thread termination.
  2. Use a Runnable with similar decoration, perhaps as a wrapper around the supplied Runnable. A variant of this is to subclass Thread in order to apply this wrapper at construction time.
  3. Create a 2nd thread to join() on the real thread and thus detect its termination.
  4. Use instrumentation to rewrite the Thread.run() method as above.
like image 40
Darron Avatar answered Dec 27 '22 07:12

Darron