Last active
July 7, 2016 21:28
-
-
Save zhangkun83/d18e91956cc8ecc32610c6571fba2e15 to your computer and use it in GitHub Desktop.
POC: using ResettableTimer to implement KeepAliveManager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class KeepAliveManager { | |
ResettableTimer shutdownTimer = new ResettableTimer() { | |
@Override | |
void timerExpired(TimerState state) { | |
synchronized (lock) { | |
if (!state.isCancelled()) { | |
transport.shutdownNow(); | |
} | |
} | |
} | |
}; | |
ResettableTimer keepAliveTimer = new ResettableTimer() { | |
@Override | |
void timerExpired(TimerState state) { | |
boolean shouldPing = false; | |
synchronized (lock) { | |
if (!state.isCancelled()) { | |
// false means shutdownTimer is already set, thus we don't need to send another ping. | |
shouldPing = shutdownTimer.tryStart(); | |
} | |
} | |
if (shouldPing) { | |
transport.ping(pingCallback); | |
} | |
} | |
}; | |
PingCallback pingCallback = new PingCallback() { | |
@Override | |
public void onSuccess() { | |
synchronized (lock) { | |
shutdownTimer.stop(); | |
keepAliveTimer.resetAndStart(); | |
} | |
} | |
@Override | |
public void onFailure() { | |
transport.shutdownNow(); | |
} | |
}; | |
void onDataReceived() { | |
synchronized (lock) { | |
keepAliveTimer.resetAndStart(); | |
} | |
} | |
void onTransportActive() { | |
synchronized (lock) { | |
keepAliveTimer.resetAndStart(); | |
} | |
} | |
void onTransportIdle() { | |
synchronized (lock) { | |
keepAliveTimer.stop(); | |
shutdownTimer.stop(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line 34: it's a bit more complicated than simply doing "keepAliveTimer.resetAndStart();" after we receive the ping response. onTransportIdle might have been called already so we shouldn't start the timer at this time. I think we probably need more state than "started" and "stopped".