0

I have a class XYZ which extends Thread and it is also a singleton (Yes. My application needs that).

In the run method, I have something like this:

public void run() {
    service.start();
}

The time it takes for service.start() is huge. Also, my application will not always need the thread to be run but can't decide in advance so while launching the application I am starting this thread.

Now, when application doesn't need the thread, it gets completed very quickly and all I need to do is wait for thread to die.

I tried to use stop() method but came to know that it is deprecated.

sachinpkale
  • 989
  • 3
  • 14
  • 35

4 Answers4

2

See this article for alternatives to calling stop()

http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

Nick Garvey
  • 2,980
  • 24
  • 31
1

stop has been deprecated a long time ago and should not be used. Thread termination is a cooperative process in Java (i.e. the interrupted code must do something when asked to stop, not the interrupting code) - one way is to call thread.interrupt() on the thread you need to interrupt.

You then need to catch the generated interrupted exception in the running thread or check the interrupted status regularly. Once the running thread detects that is should stop what it's doing, you can then run any cleanup tasks as required and exit whatever you were doing.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • This is [one way](http://stackoverflow.com/questions/3194545/how-to-stop-a-java-thread-gracefully?rq=1) - This is [another one](http://stackoverflow.com/a/8649955/829571). But as @MarkoTopolnik pointed out, without knowing what `service.start()` is doing it is hard to tell which solution would be better. Ideally, if it throws InterruptedException (and handles it properly), you can simply interrupt it. – assylias Jun 29 '12 at 09:15
  • Why all these examples are assuming that thread is executing a loop in its run method? – sachinpkale Jun 29 '12 at 09:27
  • If service.start throws InterruptedException, you don't need a loop - see my second link (although service.start will probably have a loop somewhere to check the interrupted status). – assylias Jun 29 '12 at 09:37
0

Signal your thread to do it's cleanup stuff, which you said is fast anyway, then just do a Thread.join.

Gergely Szilagyi
  • 3,813
  • 1
  • 14
  • 12
0

Your question is highly dependant on exactly what is going on in service.start(). If it's opening external resources, then naturally you can't just barge in and kill the thread without proper cleanup. The start procedure will need to be coded explicitly for interruptibility with proper cleanup.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • ok. thanks. but **service** is an object of external library class. And I don't get the point of proper cleanup. – sachinpkale Jun 29 '12 at 11:46