Skip to content

Instantly share code, notes, and snippets.

@zhangkun83
Last active July 7, 2016 21:28
Show Gist options
  • Save zhangkun83/d18e91956cc8ecc32610c6571fba2e15 to your computer and use it in GitHub Desktop.
Save zhangkun83/d18e91956cc8ecc32610c6571fba2e15 to your computer and use it in GitHub Desktop.
POC: using ResettableTimer to implement KeepAliveManager
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();
}
}
}
@zsurocking
Copy link

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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment