Skip to content

Instantly share code, notes, and snippets.

@apangin
Last active January 18, 2023 03:59
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 apangin/dc98d50868696dbb430ec8085e686c3a to your computer and use it in GitHub Desktop.
Save apangin/dc98d50868696dbb430ec8085e686c3a to your computer and use it in GitHub Desktop.
import java.io.Serializable;
import java.util.concurrent.atomic.LongAdder;
public class ReaderThread extends Thread {
private static final LongAdder ops = new LongAdder();
interface Reader extends Serializable {
boolean advanceTo(int docId);
}
private final Reader reader;
public ReaderThread(Reader reader) {
this.reader = reader;
}
public final boolean advanceTo(int docId) {
// Slow
return ((Reader) (Object) reader).advanceTo(docId);
// Fast
// java.util.Objects.requireNonNull(reader);
// return reader.advanceTo(docId);
}
public static void main(String[] args) throws Exception {
new ReaderThread(docId -> (docId & 1) == 1).start();
new ReaderThread(docId -> (docId & 1) != 0).start();
while (true) {
Thread.sleep(1000);
System.out.println(ops.sumThenReset() + " ops/sec");
}
}
@Override
public void run() {
while (benchmark()) {
ops.increment();
}
}
private boolean benchmark() {
for (int i = 0; i < 1000000; i++) {
if (advanceTo(i) && !(reader instanceof Serializable)) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment