Skip to content

Instantly share code, notes, and snippets.

@bjpeterdelacruz
Created July 14, 2023 23:55
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 bjpeterdelacruz/a0e0859982100fcb6a0270501a316a45 to your computer and use it in GitHub Desktop.
Save bjpeterdelacruz/a0e0859982100fcb6a0270501a316a45 to your computer and use it in GitHub Desktop.
This code demonstrates a race condition when the object that is used as a lock is pointing to a new reference.
// MyObject.java: https://gist.github.com/bjpeterdelacruz/b1a5b14f3d222fb30468b6edf4f3ce82
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
Runnable runnableA = MyObject::doSomething;
Runnable runnableB = MyObject::reinitialize;
for (var idx = 0; idx < 1000; idx++) {
var threads = IntStream.range(0, 1000)
.mapToObj(i -> new Thread(i % 2 == 0 ? runnableA : runnableB))
.toList();
threads.forEach(Thread::start);
threads.forEach(t -> {
try {
t.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
if (MyObject.getCounter() != 100000) {
System.out.println("Race condition occurred. Counter value: " + MyObject.getCounter());
}
MyObject.resetCounter();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment