Created
July 14, 2023 23:55
-
-
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.
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
// 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