2121import java .util .Timer ;
2222import java .util .TimerTask ;
2323import java .util .concurrent .TimeoutException ;
24+ import java .util .concurrent .atomic .AtomicBoolean ;
2425
2526/**
2627 * Created by mythz on 2/9/2017.
@@ -47,7 +48,7 @@ public class ServerEventsClient implements AutoCloseable {
4748
4849 private Date lastPulseAt ;
4950 private Thread bgThread ;
50- private boolean stopped ;
51+ private final AtomicBoolean stopped = new AtomicBoolean ( false ) ;
5152
5253 static int BufferSize = 1024 * 64 ;
5354 static int DefaultHeartbeatMs = 10 * 1000 ;
@@ -162,6 +163,7 @@ public ServerEventsClient start(){
162163 bgThread = null ;
163164 }
164165
166+ stopped .set (false );
165167 bgThread = new Thread (new EventStream (this ));
166168 bgThread .start ();
167169 lastPulseAt = new Date ();
@@ -173,7 +175,7 @@ public synchronized void restart() {
173175 try {
174176 internalStop ();
175177
176- if (stopped )
178+ if (stopped . get () )
177179 return ;
178180
179181 try {
@@ -210,7 +212,7 @@ private void sleepBackOffMultiplier(int continuousErrorsCount) throws Interrupte
210212 }
211213
212214 public synchronized void stop (){
213- stopped = true ;
215+ stopped . set ( true ) ;
214216 internalStop ();
215217 }
216218
@@ -295,6 +297,9 @@ private void startNewHeartbeat() {
295297 if (connectionInfo == null || connectionInfo .getHeartbeatUrl () == null )
296298 return ;
297299
300+ if (stopped .get ())
301+ return ;
302+
298303 if (heratbeatTimer != null )
299304 heratbeatTimer .cancel ();
300305
@@ -314,6 +319,9 @@ public void Heartbeat(){
314319 if (connectionInfo == null )
315320 return ;
316321
322+ if (stopped .get ())
323+ return ;
324+
317325 long elapsedMs = (new Date ().getTime () - lastPulseAt .getTime ());
318326 if (elapsedMs > connectionInfo .getIdleTimeoutMs ())
319327 {
@@ -330,7 +338,16 @@ public void Heartbeat(){
330338 if (Log .isDebugEnabled ())
331339 Log .d ("[SSE-CLIENT] Sending Heartbeat..." );
332340
333- String response = Utils .readToEnd (conn );
341+ try {
342+ String response = Utils .readToEnd (conn .getInputStream (), "UTF-8" );
343+ } catch (FileNotFoundException notFound ) {
344+
345+ if (stopped .get ())
346+ return ;
347+
348+ Log .e (conn .getResponseMessage (), notFound );
349+ throw notFound ;
350+ }
334351
335352 if (Log .isDebugEnabled ())
336353 Log .d ("[SSE-CLIENT] Heartbeat sent to: " + heartbeatUrl );
0 commit comments