Last active
January 18, 2023 03:59
-
-
Save apangin/dc98d50868696dbb430ec8085e686c3a to your computer and use it in GitHub Desktop.
This file contains 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
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