Skip to content

Instantly share code, notes, and snippets.

@Swarnim-singhal
Last active September 11, 2019 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Swarnim-singhal/e87baa2a3ae9cc6b0b82978a66582431 to your computer and use it in GitHub Desktop.
Save Swarnim-singhal/e87baa2a3ae9cc6b0b82978a66582431 to your computer and use it in GitHub Desktop.
EndpointState
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
public class EndpointState {
private volatile HeartBeatState hbState;
private final AtomicReference<Map<ApplicationState, VersionedValue>> applicationState;
/* fields below do not get serialized */
private volatile long updateTimestamp;
private volatile boolean isAlive;
public EndpointState(HeartBeatState initialHbState) {
this(initialHbState, new EnumMap<ApplicationState, VersionedValue>(ApplicationState.class));
}
EndpointState(HeartBeatState initialHbState, Map<ApplicationState, VersionedValue> states) {
hbState = initialHbState;
applicationState = new AtomicReference<Map<ApplicationState, VersionedValue>>(new EnumMap<ApplicationState,VersionedValue>(states));
updateTimestamp = System.nanoTime();
isAlive = true;
}
HeartBeatState getHeartBeatState() {
return hbState;
}
void setHeartBeatState(HeartBeatState newHbState) {
updateTimestamp(); hbState = newHbState;
}
public VersionedValue getApplicationState(ApplicationState key) {
return applicationState.get().get(key);
}
public Set<Map.Entry<ApplicationState, VersionedValue>> states() {
return applicationState.get().entrySet();
}
public void addApplicationState(ApplicationState key, VersionedValue value) {
addApplicationStates(Collections.singletonMap(key, value));
}
public void addApplicationStates(Map<ApplicationState, VersionedValue> values) {
addApplicationStates(values.entrySet());
}
public void addApplicationStates(Set<Map.Entry<ApplicationState, VersionedValue>> values)
{
while (true) {
Map<ApplicationState, VersionedValue> orig = applicationState.get();
Map<ApplicationState, VersionedValue> copy = new EnumMap<ApplicationState, VersionedValue>(orig);
for (Map.Entry<ApplicationState, VersionedValue> value : values)
copy.put(value.getKey(), value.getValue());
if (applicationState.compareAndSet(orig, copy))
return;
}
}
public long getUpdateTimestamp() {
return updateTimestamp;
}
void updateTimestamp() {
updateTimestamp = System.nanoTime();
}
public boolean isNormalState() {
return getStatus().equals(VersionedValue.STATUS_NORMAL);
}
public String getStatus() {
VersionedValue status = getApplicationState(ApplicationState.STATUS_WITH_PORT);
return status.value;
}
public String toString() {
return "EndpointState: HeartBeatState = " + hbState + ", AppStateMap = " + applicationState.get();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment