source: ntrip/trunk/GnssCenter/thrift/bidi_java/client/ConnectionRequiredRunnable.java@ 6682

Last change on this file since 6682 was 4940, checked in by mervart, 12 years ago
File size: 2.4 KB
Line 
1package com.joelpm.bidiMessages.client;
2
3import org.apache.log4j.Logger;
4
5/**
6* An abstract class that can be extended by tasks requiring a connection
7* to the server. Provides utility methods for a task to notify others that
8* the connection has been dropped as well as be paused until the connection
9* is resumed.
10*
11* @author Joel Meyer
12*/
13public abstract class ConnectionRequiredRunnable implements ConnectionStatusListener, Runnable {
14 private static final Logger LOGGER = Logger.getLogger(ConnectionRequiredRunnable.class);
15 protected final ConnectionStatusMonitor connectionMonitor;
16 protected final String threadName;
17 protected Thread executingThread;
18
19 public ConnectionRequiredRunnable(ConnectionStatusMonitor connectionMonitor, String name) {
20 this.connectionMonitor = connectionMonitor;
21 this.connectionMonitor.addListener(this);
22 this.threadName = name;
23 }
24
25 /**
26* Should be called if the task determines that the connection has
27* been dropped.
28*/
29 protected void disconnected() {
30 LOGGER.info(String.format("%s detected a disconnect from the server.", threadName));
31 connectionMonitor.disconnected(this);
32 connectWait();
33 }
34
35 /**
36* Can be called by the task upon startup to halt execution until
37* the connection to the server has been established.
38*/
39 protected synchronized void connectWait() {
40 executingThread = Thread.currentThread();
41 try {
42 LOGGER.info(String.format("%s waiting for connection to be established.", threadName));
43 wait();
44 } catch (InterruptedException e) {
45 LOGGER.debug(String.format("%s caught InterruptedException:", threadName));
46 LOGGER.debug(e);
47 }
48 LOGGER.info(String.format("%s notified of connection, resuming execution", threadName));
49 }
50
51 /**
52* Interrupts the executing thread which is most likely blocked on
53* 1) socket read (in the case of the MessageReceiver)
54* 2) queue read (in the case of the MessageSender)
55* Regardless of what it's up to, when the thread is interrupted
56* it will wait until notified of reconnection, at which point it
57* will resume sending/receiving.
58*
59* @see com.joelpm.bidiMessages.client.ConnectionStatusListener#connectionLost()
60*/
61 public synchronized void connectionLost() {
62 executingThread.interrupt();
63 }
64
65 /**
66* Notifies the waiting thread so that execution is resumed.
67*
68* @see com.joelpm.bidiMessages.client.ConnectionStatusListener#connectionEstablished()
69*/
70 public synchronized void connectionEstablished() {
71 notifyAll();
72 }
73}
74
Note: See TracBrowser for help on using the repository browser.