com.kolibrifx.plovercrest.server.internal.AtomicTableInfo Maven / Gradle / Ivy
Show all versions of plovercrest-server Show documentation
/*
* Copyright (c) 2010-2017, KolibriFX AS. Licensed under the Apache License, version 2.0.
*/
package com.kolibrifx.plovercrest.server.internal;
/**
* A collection of variables that should to be updated atomically so that readers get a consistent
* view as entries are written. This class is designed to update the variables without allocating
* extra memory.
*
* This class supports a single writer, and multiple readers. Write calls (update and set functions)
* have to be synchronized externally.
*/
public final class AtomicTableInfo {
private static class Entry {
long lastTimestamp = -1;
long validDataLength = 0;
long firstTimestamp = -1;
long entryCount;
}
private final Entry a = new Entry();
private final Entry b = new Entry();
private volatile Entry current = a;
public long getLastTimestamp() {
return current.lastTimestamp;
}
public long getValidDataLength() {
return current.validDataLength;
}
public long getFirstTimestamp() {
return current.firstTimestamp;
}
public long getEntryCount() {
return current.entryCount;
}
public void updateAtomically(final long lastTimestamp, final long validDataLength, final long firstTimestamp,
final long entryCount) {
final Entry otherEntry = current == a ? b : a;
otherEntry.lastTimestamp = lastTimestamp;
otherEntry.validDataLength = validDataLength;
otherEntry.firstTimestamp = firstTimestamp;
otherEntry.entryCount = entryCount;
current = otherEntry; // atomic flip
}
public void setFirstTimestamp(final long firstTimestamp) {
updateAtomically(getLastTimestamp(), getValidDataLength(), firstTimestamp, getEntryCount());
}
}