About thread stop

In API, thread.stop() is deprecated.
If i want to stop a thread, how can i have the same effect like stop()?
Thanks

You might also have to call notify() on the thread if it is in a wait() mode.
- K
Use a boolean at the top of your run() method:
boolean bStop = false;
public void run() {
if(bStop) return;
// else do whatever run() is supposed to do
bStop is a global whish you set depending on
conditions in your program. If the condition to stop
the loop becomes true, then you set bStop to true and
run() will exit.
Then you can set your reference to the thread to null
and wait for the GC() to clean up after it. This is
the recommended way to stop a thread.

Similar Messages

  • Thread.stop() -- Why is it deprecated ? - What alternatives ?

    Hi,
    I'm creating an XMPP server in Java and I have a problem. I have a thread that run the SAX parser and is constantly blocking to recive data from my socket. Now the problem is that at some point (after the authentication) I need to stop the XML parsing.
    The only way I can do this, I think, is by using the Thread.stop() method, but it is deprecated :(
    I read the FAQ about this deprecation but the alternatives given can't work for me:
    - I can't close the eocket because I need to read another XML document right after on the socket
    - I can't call Thread.interrupt() because the thread is blocking on an IO
    - I can't use a shared variable because the thread is blocked inside the SAX parser that call from time to time a callback. I can't modify the SAX code :(
    Does anyone have an idea how to make my thread stop the parsing ?
    Thanks
    Mildred

    If you've read the "FAQ" on deprecation of stop etc then you already know why stop() is deprecated - it is inherently unsafe as you can't know for sure what your thread was doing when you tried to stop it. Further, what those documents don't tell you is that Thread.stop doesn't break you out of most blocking situations any way - so it wouldn't necessarily help even if it weren't deprecated.
    I don't know the I/O or threading architecture of what you are working with so the following may not be applicable, but hopefully something will help:
    One of the alternatives you didn't mention is setting the SO_TIMEOUT option on the socket so that your thread can periodically check if its actually been cancelled. I don't know if that is possible in this case it depends on how the use of sockets gets exposed by the library.
    Other possibilities for unblocking a thread are to give the thread what it is waiting for - some data on the socket in this case. If you can send something that can be interpreted as "stop looking for more data", or if you check for cancellation before trying to interpret the data at all, then you can unblock the thread by writing to the socket. Whether this is feasible depends on how the real data is written to the socket.
    Final possibility is to create a new thread to do the socket reading. Your parser thread can then read from a BlockingQueue, for example, that is populated with data from the socket thread. You can use interrupt() to cancel the parser thread and just ignore the socket thread - which presumably will unblock when the next real data arrives.

  • Is there a better way to stop a Method than Thread.stop()?

    First my basic problem. In one of my programs I am using constraint solver. I call the constraint solver with a set of constraints and it returns a Map with a satisfying assignment. In most cases this works in acceptable time ( less than 1 second). But in some cases it may take hours. Currently I am running the function in a Thread and using Thread.stop(). This look like that:
         public Map<String, Object> getConcreteModel(
                   Collection<Constraint> constraints) {
              WorkingThread t=new WorkingThread(constraints);
              t.setName("WorkingThread");
              t.start();
              try {
                   t.join(Configuration.MAX_TIME);
              } catch (InterruptedException e) {
              if(t.isAlive()){
                   t.stop();
              return t.getSolution();
         }where t.getSolution(); returns null if the Thread was interrupted.
    Unfortunately this sometimes crashes the JVM with:
    # A fatal error has been detected by the Java Runtime Environment:
    #  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000006dbeb527, pid=5788, tid=4188
    # JRE version: 6.0_18-b07
    # Java VM: Java HotSpot(TM) 64-Bit Server VM (16.0-b13 mixed mode windows-amd64 )
    # Problematic frame:
    # V  [jvm.dll+0x3fb527]
    # An error report file with more information is saved as:
    # F:\Eigene Dateien\Masterarbeit\workspace\JPF-Listener-Test\hs_err_pid5788.log
    # If you would like to submit a bug report, please visit:
    #   http://java.sun.com/webapps/bugreport/crash.jsp
    #Does anyone knows a better way to do it?
    Thank you in advance.
    Note 1: the Constraint solver is a Third Party tool and changing it is unfeasible. (I have tried it already)
    Note 2: Using Thread.stop(Throwable t) only chances the error message.

    In case somebody have the same problem here my code which solves the problem. Note it requires to parameters and the result to be serializable.
    The Class which starts to Process:
    public class Solver{
         public Map<String, Object> getConcreteModel(
                   Collection<Constraint> constraints) {
                   try
                        Process p=Runtime.getRuntime().exec(...); //do not forget the classpath
                        new TimeOut(Configuration.MAX_TIME, p).start();
                        ObjectOutputStream out=new ObjectOutputStream(p.getOutputStream());
                        new ErrReader(p.getErrorStream()).start();//not that std.err fills up the pipe
                        out.writeObject(constraints);
                        out.flush();
                        ObjectInputStream in=new ObjectInputStream(p.getInputStream());
                        return (Map<String, Object>) in.readObject();
                   catch(IOException e)
                        return null;
                   } catch (ClassNotFoundException e) {
                        //should not happen
                        return null;
         // For running in a own process
         static private class TimeOut extends Thread
              private int time;
              private Process p;
              public TimeOut(int time, Process p)
                   this.time=time;
                   this.p=p;
              @Override
              public void run() {
                   synchronized (this) {
                        try {
                             this.wait(time);
                        } catch (InterruptedException e) {
                   p.destroy();
         static class ErrReader extends Thread
             InputStream is;
             ErrReader(InputStream is)
                 this.is = is;
                 this.setDaemon(true);
             public void run()
                 try
                     InputStreamReader isr = new InputStreamReader(is);
                     BufferedReader br = new BufferedReader(isr);
                     String line=null;
                     while ( (line = br.readLine()) != null)
                         System.err.println(line);   
                     } catch (IOException ioe)
                         ioe.printStackTrace(); 
    }And the class which executet the Program
    public class SolverProcess {
          * @param args ignored
         public static void main(String[] args){
              try {
                   ObjectInputStream in =new ObjectInputStream(System.in);
                   SolverProcess p=new SolverProcess();
                   p.constraints=(Collection<Constraint>) in.readObject();
                   p.compute();
                   ObjectOutputStream out=new ObjectOutputStream(System.out);
                   out.writeObject(p.solution);
                   out.flush();
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              //System.err.println("solved");
              System.exit(0);
         private Map<String, Object> solution=null;
         private Collection<Constraint> constraints;
           private void compute()
    }

  • All Application threads stopped for 3~5 minutes

    Hi.
    Our Java application experiences sudden 3~5 minutes application threads stops.
    Our Application is run by 1 process and 300~400 threads.
    All threads are stopped suddenly and are run after 3~5 minutes or more.
    I can't analyze any patten but I experience this problem once or twice a day.
    I guess it is caused by application bug, java bug or Solaris bug and so on.
    I have difficulty to solve this problem and I can't find what causes it.
    Please give advice on this problem.
    (*) Our system :
    SunOS Solaris 5.10 Generic_138888-03 sun4u sparc SUNW,Sun-Fire-V890 (32G Mem)
    (*) Java :
    java version "1.5.0_12"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_12-b04)
    Java HotSpot(TM) Server VM (build 1.5.0_12-b04, mixed mode)
    (*) Java Options
    -mx2048m -Dcom.sun.management.jmxremote.port=16000
    -Dcom.sun.management.jmxremote.authenticate=false
    -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.snmp.interface=`hostname`
    -Dcom.sun.management.snmp.acl=false -Dcom.sun.management.snmp.port=16500 -Xcheck:jni
    -XX:+PrintGCDetails -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGCApplicationStoppedTime

    Show your GC logs.

  • Replacement for Thread.stop( ) in JDk 1.4

    Hi all,
    Please suggest an alternate solution to this issue.
    1. Thread problem :
    We cannot use System.exit(0) because control goes out of the calling program also.
    We cannot use destroy() because after the Thread.currentThread().destroy(), the program doesnot know how to handle it and it throws up an exception.
    java.lang.NoSuchMethodError
    at java.lang.Thread.destroy(Unknown Source) // also thread.destroy is deprecated
    The other solution that I explored is the use of interrupt(). However, if I try Thread.currentThread.isAlive() , then it returns me TRUE - meaning , that the thread was not killed or stopped. Because of this, the applet does not exit.
    Remaining options:
    Setting the thread to null. Explore more on how to use set the Thread.currentThread to null?
    Applet {
    init{
    new Thread(){
    public void run(){
    }.start();
    exit(){
    Thread.currentThread().stop();
    the focus here has to be what needs to be done to the Thread.currentThread().stop()?
    In case, we cannot find a solution, can we rewrite the applet without Thread.stop() to do the same? Will it exit then? Can you try it?
    Please reply with your suggestions at the earliest.
    Regards
    Abhijeet

    put some while loop in your run() method as follows
    public void run()
    while(flag)
    //do something
    here flag is a boolean variable. Then to stop the running thread, set flag to false from some other thread.

  • ABOUT THREADS

    Cound Sun provide some official material about Threads ? Because its such an important feature and there is little to none material on this topic in this language while in Java there are hundreds of links to choose from, here you have to go with what is available and it isnt much. There are only 3 links to external sites in the javafx HOW TO'S. They just give the basics but no solid examples of using threads in fx, I needed a client/server example in fx that doesnt hang the interface so i could take off from there. So please sun post some material about threading in fx other than just giving external links!!!

    http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html

  • Question while Learning about Thread

    I am learning about thread.
    I ran the sample producer/consumer programe in Java Thread Tutorial in which I added two lines of printing out codes in class CubbyHole to observe the runing sequence better.
    The result made me a bit confused. I imagine that the result "Producer #1 put: 1" should be printed out right after "put 1", why it appeared after "get 1" and "Consumer #1 got: 1"?
    Codes are listed below:
    public class ProducerConsumerTest {
    public static void main(String[] args) {
    CubbyHole c = new CubbyHole();
    Producer p1 = new Producer(c, 1);
    Consumer c1 = new Consumer(c, 1);
    p1.start();
    c1.start();
    public class Producer extends Thread {
    private CubbyHole cubbyhole;
    private int number;
    public Producer(CubbyHole c, int number) {
    cubbyhole = c;
    this.number = number;
    public void run() {
    for (int i = 0; i < 10; i++) {
    cubbyhole.put(i);
    System.out.println("Producer #" + this.number
    + " put: " + i);
    try {
    sleep((int)(Math.random() * 100));
    } catch (InterruptedException e) { }
    public class Consumer extends Thread {
    private CubbyHole cubbyhole;
    private int number;
    public Consumer(CubbyHole c, int number) {
    cubbyhole = c;
    this.number = number;
    public void run() {
    int value = 0;
    for (int i = 0; i < 10; i++) {
    value = cubbyhole.get();
    System.out.println("Consumer #" + this.number
    + " got: " + value);
    public class CubbyHole {
    private int contents;
    private boolean available = false;
    public synchronized int get() {
    while (available == false) {
    try {
    wait();
    } catch (InterruptedException e) { }
    available = false;
    System.out.println("get " + contents);
    notifyAll();
    return contents;
    public synchronized void put(int value) {
    while (available == true) {
    try {
    wait();
    } catch (InterruptedException e) { }
    contents = value;
    System.out.println("put " + contents);
    available = true;
    notifyAll();
    The result is as below:
    put 0
    Producer #1 put: 0
    get 0
    Consumer #1 got: 0
    put 1
    get 1
    Consumer #1 got: 1
    Producer #1 put: 1
    put 2
    get 2
    Consumer #1 got: 2
    Producer #1 put: 2
    put 3
    get 3
    Consumer #1 got: 3
    Producer #1 put: 3
    put 4
    get 4
    Consumer #1 got: 4
    Producer #1 put: 4
    put 5
    get 5
    Consumer #1 got: 5
    Producer #1 put: 5
    put 6
    get 6
    Consumer #1 got: 6
    Producer #1 put: 6
    put 7
    get 7
    Consumer #1 got: 7
    Producer #1 put: 7
    put 8
    get 8
    Consumer #1 got: 8
    Producer #1 put: 8
    put 9
    Producer #1 put: 9
    get 9
    Consumer #1 got: 9

    Hi alaska,
    The reason you got those results are because these are
    threads. The execution of the order of thread is
    always random (unless some explicit logic is applied)
    and CPU can execute any thread at any time within the
    process. So the results you got are perfectly right.
    Even the order of the output may change everytime you
    run the same program.
    -- manishI think you can change the predictability by setting the Producer's thread priority has higher than the Consumer's...

  • Looking for a good book about threads

    Hello all,
    I am looking for a good book about threads.
    I would like something which is both practical, but also provides some theoretical basis.
    I am an experienced programmer, with some, but not much, experience with concurrent design.
    I would greatly appreciate any suggestions.

    I found the "Java Threads" book by Oaks and Wong to be fantastic:
    http://www.oreilly.com/catalog/jthreads2/
    - K
    Hello all,
    I am looking for a good book about threads.
    I would like something which is both practical, but
    also provides some theoretical basis.
    I am an experienced programmer, with some, but not
    much, experience with concurrent design.
    I would greatly appreciate any suggestions.

  • My license is about to stop

    I've got this automail from Adobe that my Creative Cloud is about to be terminated.
    Shouldn't that be renewed automatically when we are joining the Adobe Community Professionals Program ?

    Hi Mohd!
    I know that site, but that's when I want to buy an extra year, and that
    wasn't my intention
    2014-07-22 21:24 GMT+02:00 Mohd Naseem <[email protected]>:
        My license is about to stop  created by Mohd Naseem
    <https://forums.adobe.com/people/Mohd+Naseem> in Premiere Pro - View
    the full discussion <https://forums.adobe.com/message/6573792#6573792>

  • Trying to learn about threads

    Hi guys,
    I'm trying to learn more about threads......i've written a small program for a better understand, but i don't understand the order of the output i'm getting:
    public class testme {
    public static void main(String[] args) {
    Theshape mover = new Theshape("go");
         mover.start();
    System.out.println ("checkpoint 1");
    System.out.println ("checkpoint 2");
         }//main
    }//class testme
    class Theshape extends Thread {
    public int count;
    public String thego;
    Theshape (String gg){
         thego= gg;
    count=0;
    }//constructor
    public void run(){
    try {
    do{
    System.out.println (thego);
    sleep(1000);
    System.out.println ("johnny");
    count=count+1;
    }while(count<8);
    } catch (InterruptedException e) {}
    }//run          
    }//class theshape
    ........the output i get is:
    checkpoint 1
    checkpoint 2
    go
    johnny
    go
    johnny
    go
    johnny
    go
    johnny
    go
    johnny
    go
    johnny
    go
    johnny
    go
    johnny
    I would like to know why "checkpoint 1" and "checkpoint 2" is printed first, even though the call to the run method is made before the two statements. i would have thought that the two checkpoint statements would be printed last.
    Can anyone help?
    Thanks,
    Zaf

    After you've issued the 'mover.start()' call, a new thread pops into existence. The first thread (your main thread) continues to run while the second thread prepares itself to start up. On your machine, this startup takes a (little) while, so your main thread is able to print those two line just before the other thread is able to print something. That's all there is to it. If you put a 'Thread.sleep(1234)' between those two println statements in your main thread, the output would probably be a bit different. Give it a try.
    kind regards,
    Jos

  • How to stop a thread without the deprecated Thread.stop() method?

    Hi,
    I am writting a server application that launches threads, but the run() implementation of these threads are not written by me (i.e. i have no control over them): they are third-party programs. That's why i could not use the well known Java tutorial way to stop a thread (i.e. with a global variable that indicates the thread state).
    I would like my server to be able to stop these threads at any time, but without using the deprecated Thread.stop() method.
    Any ideas ?
    Thanks in advance,
    Fabien

    Thanks Pandava!
    I was arrived at the same conclusion... As to me, it is a very bad issue, because it means for example that a servlet server can not stop any servlet it launches (especially for preventing infinite loops).
    If i want to be strictly JDK 1.4 compliant, i should not use Thread.stop(). But if i don't use it, i don't have any ideas of how stop a thread that i don't control...

  • Dumb question about Thread Safety in Servlets

    Hi all
    I wrote this Client API for sending requests and receiving responses to / from a multivalue database. The API is called by my Servlet. Now it seems my API is not thread safe because when several people open up the servlet at the same time, the API gets totally confused. When the API calls are inside a synchronized(){} it works just fine, but obviously at a big performance hit. Is that the wrong way of doing it??
    However when I was doing the ACID test locally on my machine, by opening two command prompts and excuting the same java program (with the same code in it as the servlet, but standalone) my API worked just fine. How come?
    Any insights appreciated as I am just learning about thread safety now (the hard way :-( )
    cheers
    Dejan

    Does this help
    Are you using one connection to the database shared by all instances
    of your servlet
    And is this connection create in the init method of the servlet and stored
    in the servlet context.
    Problem 4 people try and use your servlet at the same time, each servlet trys to
    create a connection to the database and then store it in the servlet context and
    this causes a problem.
    Solution create a listener to create the connection and store it in the servlet context
    when the servlet is created.
    If this is your problem it is not advisable to use only one connection to the db
    try using db pooling

  • Is there any alternative to Thread.stop();

    Hi everybody,
    I am facing troubles ,while stopping the Thread. at present i am using 'Thread.destroy()', because Thread.stop() was deprecated.#
    Is there any alternative for Thread.Stop()
    Thanks in advance!
    bye

    boolean myThreadShouldRun;
    public void run()
    while (myThreadShouldRun)
    doSomeThing();
    to stop the thread use: myThreadShouldRun=false; from outside the thread and it will stop the natural way. forcing threads to stop with the stop method was dangerous and therefore this method is deprecated and will maybe not be supported in future releases.

  • JDWP fatal error from thread.stop()

    I get this message
    FATAL ERROR in native method: JDWP "util.c" (Jan 20 2004), line 1209: Unexpected error, error code = 113 (JVMDI_ERROR_INTERNAL)
    from the target VM when I do thread.stop() on the debugger side. The debugger isn't bothered by the fatal error, but the target dies.
    Can anyone offer a clue to what I did wrong?
    Peter

    FATAL ERROR in native method: JDWP "util.c" (Jan 20
    2004), line 1209: Unexpected error, error code = 113
    (JVMDI_ERROR_INTERNAL)
    from the target VM when I do thread.stop() on the
    debugger side. The debugger isn't bothered by the
    fatal error, but the target dies.
    Can anyone offer a clue to what I did wrong?Lets see... "Jan 20 2004" implies that you are using the Tiger (1.5)
    beta release for this experiment.
    According to the JDWP spec:
    http://java.sun.com/j2se/1.5.0/docs/guide/jpda/jdwp/jdwp-protocol.html
    Error 113 is "An unexpected internal error has occurred"
    More information, please...
    - What platform are you running on, and what version(s) of the VM
    are you using?
    - Which thread in the debugee did you send the stop() to?
    - Can you update this article with sample code and a narrative
    describing what happened when?
    - What throwable did you pass to com.sun.jdi.ThreadReference.stop(ObjectReference throwable)

  • Reading about threads. Where?

    Hi!
    I need to read up a bit about threads. I know the ideas behind them, but I need to know how to handle threads and write code for them in java. Does anyone have any tips about good tutorials or something?
    Thanks.

    Look out at
    1. Java Tutorial (http://java.sun.com/docs/books/tutorial/essential/threads/definition.html)
    (A must to begin with !! )
    2. www.javaworld.com Articles (search on "Java Thread")
    (Really nice !)
    3. http://directory.google.com/Top/Computers/Programming/Threads/Java/
    (Lots of stuffs!!)
    4. There are many books available on Java Thread. Even Core Java Programming from Sun Press has chapter in Multithreading. Dedicated book on Java Thread Programming is also available for serious programmers. :)
    Hope this helps.
    Regards,
    Rahul

Maybe you are looking for

  • Query for geetiing no.of working days

    Hi All, How can we write a query for geetiing no.of working days in Oracle Apps. Basically we need to mention no.of working days in the Work-Flow Form but not the no.of days. So how can we write a query for getting no.of working days.and Where can we

  • How to hold the government's stock under our location

    Hi All, We have a scenario where in we need to hold the stock of some government's material in our plant /warehouse. The government agrees to pay for the storage for whatever period of time we need to . What I want to know is 1. Though the stock is a

  • Gantt chart with duration

    Hi Experts As a part of bidding, client need to produce Gantt chart to the customer. However, since this is presale process, the exact dates are not indicated but the duration of project to be specified. It means the schedule to show the duration fro

  • Security update and Adobe CS2 Suite

    there is alot being said about this but i thought i would throw this out there, as it may be helpful. i installed security update on intel macbook pro from software update. machine is nonresponsive, can move mouse but that is all. so i did an erase a

  • MY SCREEN HAS DARKER AREA ON DOWN-LEFT AND UP-RIGHT CORNERS, CAN I GET MY SCREEN REPLACED?

    the cernter part is obvious brighter and im using the safari about:blank to show a whole white screen. can i bring my computer to the genius bar and request a replacement of the screen? btw, mine is the 13-inch retina pro bought in october so it shou