0

My program is whenever i start my AccelSender program, it sends epnId to my server machine to request host for that particular epnId. When the server returns hostName, it starts two Runnable Thread class called new DataTransmitter(hostName,epnId) and new JMSConnection().

What i am trying to do is whenever my reStart(String hostName) is invoked i want to stop the new DataTransmitter(hostName,epnId) thread and start it with setting new hostName.

Here is my code:

public class AccelSender {

        private Socket kkSocket = null;
        private PrintWriter out = null;
        private BufferedReader in = null;

        private static final String epnId = "EPN1";

        public AccelSender(){
        }

        public void requestHost(){

            try{
                Socket hostSocket = new Socket("10.3.2.227",1121);
                PrintWriter out = new PrintWriter(hostSocket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(hostSocket.getInputStream()));
                out.println(epnId);
                    while(true){
                        String hostName = in.readLine();
                        DataTransmitter dt = new DataTransmitter(hostName,epnId);
                        JMSConnection jms = new JMSConnection();
                        new Thread(dt).start();
                        new Thread(jms).start();
                    }
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }

    public void reStart(String hostName){
    //Here i want to STOP the DataTransmitter Thread and,
 START with new hostName
        }

    }

Code for Runnable class:

public class DataTransmitter implements Runnable {

    private Socket kkSocket = null;
    private PrintWriter out = null;
    private BufferedReader in = null;

    private int port = 2508, fileCount = 0, arrivalRate = 500;
    private String hostName = null, data = null, filename = null;
    private boolean resetSender = false;
    private static String epnId = null;
    File folder = new File(System.getProperty("user.dir")+"/input_data");
    File[] listOfFiles = folder.listFiles();

    public DataTransmitter(){
    }


    public DataTransmitter(String hostName, String epnId){

        this.hostName = hostName;
        this.epnId = epnId;
        establishHostConnection();
    }

    public void establishHostConnection(){

        try {
            kkSocket = new Socket(hostName, port);
            out = new PrintWriter(kkSocket.getOutputStream(), true);
            in = new BufferedReader(new 
InputStreamReader(kkSocket.getInputStream()));
            resetSender = true;
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: thinklatch.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: 
thinklatch.");
            System.exit(1);
        }
    }

    public void close() throws IOException{

        kkSocket.close();
        out.close();
        in.close();
    }

    public void run(){

        System.out.println("Entering Data Transmitter");

        try{
            while (fileCount <= 1) {


                for (int i = 0; i < listOfFiles.length; i++) {
                    if (listOfFiles[i].isFile()) {
                        System.out.println("File " + 
listOfFiles[i].getName());
                        filename = System.getProperty("user.dir") + 
"/input_data/" + listOfFiles[i].getName();

                        BufferedReader bf = new BufferedReader(new 
FileReader(filename));
                        System.out.println("Fetching input from : " + 
filename);

                        while((data=bf.readLine())!=null){
                            String str = 
this.hostName+","+this.epnId+","+arrivalRate+","+data;
                            out.println(str);
                            try{
                                TimeUnit.MILLISECONDS.sleep(2);
                            }catch(Exception e){
                            }
                        }
                    }
                }
                     fileCount++;
            }
        }catch(FileNotFoundException fnfe){
            System.err.println("E"+fnfe);
        }catch(IOException ioe){
            System.err.println("E"+ioe);
        }
            out.close();
    }
}

Any advice on restarting the thread for this case is appreciable. Thanks in advance ....

Vinesh
  • 933
  • 2
  • 7
  • 22
  • 3
    Might want to take a look at the related Questions. [how-to-start-stop-restart-a-thread-in-java](http://stackoverflow.com/questions/1881714/how-to-start-stop-restart-a-thread-in-java?rq=1) and [how-to-restart-thread-in-java](http://stackoverflow.com/questions/468266/how-to-restart-thread-in-java?rq=1) – asgs Sep 18 '12 at 07:14
  • 2
    (somewhat off-topic) - you should follow Java conventions, and make all your class-names start with upper-case – tucuxi Sep 18 '12 at 07:16
  • Can you show the code of the `Runnable`? – Tudor Sep 18 '12 at 07:22
  • 2
    Could you not give the data transmitter thread instance updated config rather than stop/start? Also once you kill a thread it's dead and not restartable. You will be starting a new thread – Stephen Connolly Sep 18 '12 at 07:22

3 Answers3

4

A thread can't actually be "restarted" once the run method has finished executing. You have two options basically:

  1. Introduce a loop that causes the thread to be suspended (e.g. call a wait) when a condition is met. That way you can "pause" the thread, change the hostname and then signal it to resume.
  2. Cause the thread to finish its code, discard it and then start a new thread with the same Runnable object.

Edit: So what you can do in the restart method is to call to close method on the dt object. This will close the sockets and cause an IOException that will make the thread exit its run method. After that you can just start a new thread:

dt = new DataTransmitter(hostName,epnId);
new Thread(dt).start();
Tudor
  • 61,523
  • 12
  • 102
  • 142
  • Inside my run() i am having endless loop which transmits data... How can i stop that... – Vinesh Sep 18 '12 at 08:47
  • @Vinesh: What if the old thread is still executing code when you want to restart it? Do you want to forcibly kill it? – Tudor Sep 18 '12 at 09:06
  • What i am trying is stop data transfer to the current host & set new host and start data transfer... – Vinesh Sep 18 '12 at 09:09
1

Use Thread.currentThread().isInterrupted() and Thread.interrupt()

See this link :

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

Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82
  • 1
    (And then, after interrupting the thread, just launch a new one; you cannot restart a thread, but you can start a new one) – tucuxi Sep 18 '12 at 07:27
0

Thread once stopped can't be restarted.

- Once the thread of Execution associated with the Thread Class Instance finishes its run() method, it moves into the Dead State, or Thread Pool if implemented. The Thread Class Instance which was associated with the thread of Execution Permanently looses its Threadness.

- You can better use the wait() and notify() mechanism, and can also use await() and signal() mechanism from java.util.concurrent package, to suspend and resume the thread.

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
  • "The Instance Thread Class Instance which was associated with the thread of Execution Permanently looses its Threadness" ? – Brian Agnew Sep 18 '12 at 08:26
  • Oh don't don't don't use wait() and notify(). You should consider these "deprecated" (cf. Effective Java by Joshua Bloch) – Steve McLeod Sep 18 '12 at 08:57
  • @BrianAgnew thanks for showing the `typo`..and @SteveMcLeod thats the reason i mentioned the `await() and signal() methods.` – Kumar Vivek Mitra Sep 18 '12 at 09:29