0

I have a class which connects to a server as below.

@Override
public void run() {
    while (running) {
        try {
            msgHandler.log("Connecting to " + host + ":" + port);
            Socket s = new Socket(host, port);

            if (s.isConnected() && !s.isClosed()) {
                msgHandler.connectionInit(s);
            }
            BufferedInputStream input = new BufferedInputStream(s.getInputStream());

    }
}

The consumer which is the msgHandler, frequently polls the socket if a connection ever goes down as below.

@Override
public void connectionInit(Socket s) throws IOException {
    logger.info("Connected to AWW Service on " + configuration.getAwwHost() + ":" + configuration.getAwwPort());

    output = new BufferedOutputStream(s.getOutputStream());

    connector.componentReady();
    Timer t = new Timer();
    t.schedule(new TimerTask() {
        @Override
        public void run() {
                try {
                    pollServer();
                } catch (IOException e) {
                    // SOCKET GETS BROKEN HERE 
                }
        }
    }, 0, 25000);

}

Question is, how can i communicate from the exception i get when the socket connection gets broken back to the run() thread, so it can try to reinitialize the socket and the input stream?

I dont think a notify() or wait() mechanism is appropriate here as wait() will just put the run() thread to sleep. I was thinking whats the equivalent of setting a flag when the connection gets broken, and the run() thread constantly checks the flag, and when it is set to true, it reinitialize the socket. But i am sure there would be a more efficient multi threading approach native to java for achieving this.

Saad
  • 915
  • 9
  • 19

2 Answers2

0

I think the simplest approach is using an AtomicBoolean variable that is accessible to both threads - you could pass the variable in when constructing each thread's run class if necessary. Nice thing about AtomicBoolean is that it is already thread safe/synchronized and mutable so that it can be passed around and modified by reference.

See this similar question for some more details.

Community
  • 1
  • 1
Matt Weinecke
  • 602
  • 6
  • 17
0

I think that in the run() function, you should have a code like the following one.

// ...
try
{
    // ...
    int read = input.read(...);
    // ...

}
catch (IOException e)
{
    // TODO: terminate the thread and restart a new connection
}

So, if an error occurs during the pollServer() call, also my code above should generate an exception.

Also when you call the close function of a Socket object, the input and output streams will generate the relative exceptions.

sandromark78
  • 148
  • 1
  • 4