1 8 9 package mx4j.remote; 10 11 import java.io.IOException ; 12 import java.util.Map ; 13 14 19 public abstract class AbstractHeartBeat implements HeartBeat, Runnable 20 { 21 private final ConnectionNotificationEmitter emitter; 22 private long pulsePeriod; 23 private int maxRetries; 24 private Thread thread; 25 private volatile boolean stopped; 26 27 35 protected AbstractHeartBeat(ConnectionNotificationEmitter emitter, Map environment) 36 { 37 this.emitter = emitter; 38 if (environment != null) 39 { 40 try 41 { 42 pulsePeriod = ((Long )environment.get(MX4JRemoteConstants.CONNECTION_HEARTBEAT_PERIOD)).longValue(); 43 } 44 catch (Exception ignored) 45 { 46 } 47 try 48 { 49 maxRetries = ((Integer )environment.get(MX4JRemoteConstants.CONNECTION_HEARTBEAT_RETRIES)).intValue(); 50 } 51 catch (Exception ignored) 52 { 53 } 54 } 55 if (pulsePeriod <= 0) pulsePeriod = 5000; 56 if (maxRetries <= 0) maxRetries = 3; 57 } 58 59 public long getPulsePeriod() 60 { 61 return pulsePeriod; 62 } 63 64 public int getMaxRetries() 65 { 66 return maxRetries; 67 } 68 69 74 protected abstract void pulse() throws IOException ; 75 76 public void start() throws IOException 77 { 78 thread = new Thread (this, "Connection HeartBeat"); 79 thread.setDaemon(true); 80 thread.start(); 81 } 82 83 public void stop() throws IOException 84 { 85 if (stopped) return; 86 stopped = true; 87 thread.interrupt(); 88 } 89 90 public void run() 91 { 92 try 93 { 94 int retries = 0; 95 while (!stopped && !thread.isInterrupted()) 96 { 97 try 98 { 99 Thread.sleep(pulsePeriod); 100 101 try 102 { 103 pulse(); 104 retries = 0; 105 } 106 catch (IOException x) 107 { 108 if (retries++ == maxRetries) 109 { 110 sendConnectionNotificationFailed(); 112 break; 113 } 114 } 115 } 116 catch (InterruptedException x) 117 { 118 Thread.currentThread().interrupt(); 119 } 120 } 121 } 122 finally 123 { 124 stopped = true; 125 } 126 } 127 128 132 protected void sendConnectionNotificationFailed() 133 { 134 emitter.sendConnectionNotificationFailed(); 135 } 136 } 137 | Popular Tags |