Java Restart a Socket

521 Views Asked by At

I have a socket, which is initialized inside a thread, here is my code.

public class Receiver extends Thread {

        public static boolean connect() {
            boolean result;
            try {
                client = new Socket(serverIPString,Integer.parseInt(serverPortString));
                result = true;
            } catch (IOException e) {
                result = false;
                WriteExceptions.writeToFile(e);
            }
            return result;
        }

        public void run() {

            while (!connect()) {
                // try to connect every 30 seconds
                try {
                    TimeUnit.SECONDS.sleep(30);         
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            }
            initializeThreads();

        }

        public static void initializeThreads() {

            try {
                System.out.println("initializeThreads...");
                // create new thread pool with four threads
                application = Executors.newCachedThreadPool();
                // create ArrayBlockQueueSync to store ints
                sharedLocation = new ArrayBlockQueueSync();
                // execute tasks
                t1 = application.submit(new Reader(client.getInputStream(),sharedLocation));
                t2 = application.submit(new Writer(client.getOutputStream(),sharedLocation));

                sd = Executors.newScheduledThreadPool(2);

                t3 = sd.scheduleAtFixedRate(new LinkAlive(sharedLocation),15000, 5 * 60 * 1000, TimeUnit.MILLISECONDS);
                t4 = sd.scheduleAtFixedRate(new DBSync(sharedLocation), 5 * 60 * 1000, 24 * 60 * 60 * 1000, TimeUnit.MILLISECONDS);

            } catch (IOException e) {
                 WriteExceptions.writeToFile(e);
            }

        }

        public static void disconnect(){
            try {
                client.close();
                System.out.println("Close Socket");
                shutdownAndAwaitTermination();
            } catch (IOException e) {
                e.printStackTrace();
                WriteExceptions.writeToFile(e);
            }
        }

        public static void shutdownAndAwaitTermination() {      
            t1.cancel(true);
            t2.cancel(true);
            t3.cancel(true);
            t4.cancel(true);
            application.shutdown(); 
            sd.shutdown(); 
            try {
                if (!application.awaitTermination(60, TimeUnit.SECONDS)) {
                    application.shutdownNow(); 
                    if (!application.awaitTermination(60, TimeUnit.SECONDS))
                        System.err.println("Pool did not terminate");
                 }
                 if (!sd.awaitTermination(60, TimeUnit.SECONDS)) {
                    sd.shutdownNow();
                     if (!sd.awaitTermination(60, TimeUnit.SECONDS))
                         System.err.println("Pool did not terminate");
                 }
            } catch (InterruptedException ie) {
                WriteExceptions.writeToFile(ie);
                application.shutdownNow();
                sd.shutdownNow();   
            }
            client = null;
            reconnect();
        }

        public static void reconnect(){
            try {
                Messages.writeStringToFile("Start the countdown","RECS");
                for(int i=1; i<=60; i++){           
                    TimeUnit.SECONDS.sleep(1);
                    Messages.writeStringToFile(i+" seconds","REC");
                }
                Messages.writeStringToFile("End the countdown","RECE");

                // try to reconnect
                while (!connect()) {
                    Messages.writeStringToFile("Try to connect.","RECT");
                    // try to connect every 60 seconds
                    try {
                        TimeUnit.SECONDS.sleep(60);
                    } catch (InterruptedException ex) {
                        Thread.currentThread().interrupt();
                    }
                }
                initializeThreads();
            } catch (Exception e) {
                WriteExceptions.writeToFile(e);
            }
        }
}

This socket is used to communicate with another program. I have 4 runnables, the Reader is reading the incoming data from the socket and the other 3 is mosty writing on the socket, but on the Writer runnable, when I receive a special data, which is saying that the other program, which I communicate is going to shutdown, so I have to restart mine, here is the code.

public class Writer implements Runnable {
    @Override
    public void run() {
        ....
        // disconnect
        Receiver.disconnect();
        ....
    }
}

When the disconnect is call, I am getting a series of exceptions the first is:

java.net.SocketException: Socket closed
    at java.net.SocketInputStream.read(SocketInputStream.java:203)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at java.net.SocketInputStream.read(SocketInputStream.java:223)
    at sockets.Reader.deserialize(Reader.java:74)
    at sockets.Reader.run(Reader.java:36)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

The second exception is:

java.lang.InterruptedException
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2067)
    at java.util.concurrent.ThreadPoolExecutor.awaitTermination(ThreadPoolExecutor.java:1465)
    at sockets.Receiver.shutdownAndAwaitTermination(Receiver.java:143)
    at sockets.Receiver.disconnect(Receiver.java:124)
    at sockets.Writer.run(Writer.java:97)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

The last exceptions is:

java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at java.lang.Thread.sleep(Thread.java:340)
    at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
    at sockets.Receiver.reconnect(Receiver.java:181)
    at sockets.Receiver.shutdownAndAwaitTermination(Receiver.java:170)
    at sockets.Receiver.disconnect(Receiver.java:124)
    at sockets.Writer.run(Writer.java:97)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

After that the program is doing nothing. Maybe I have made bad design or wrong approach. Sorry for my english.

1

There are 1 best solutions below

0
On BEST ANSWER

Try closing input and output stream on the client side.

client = new Socket(serverIPString,Integer.parseInt(serverPortString));
InputStream in = client.getInputStream();
OutputStream out = client.getOutPutStream();

//Do your work with input and output stream.....

in.close();
out.close();