class Configuration {}
class ServiceRegistry {
ServiceComponent cachedServiceComponent;
void register(ServiceComponent component) {
this.cachedServiceComponent = component;
}
}
class ServiceComponent {
final Configuration config;
ServiceComponent(ServiceRegistry registry) {
registry.register(this);
// Inject some work to increase likelihood
// of an observable data race
for (int i = 0; i < 1_000_000; i++) {
Thread.yield();
}
this.config = new Configuration();
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 100_000; i++) {
ServiceRegistry registry = new ServiceRegistry();
Thread t1 = new Thread(() -> {
new ServiceComponent(registry);
});
Thread t2 = new Thread(() -> {
if (registry.cachedServiceComponent != null &&
registry.cachedServiceComponent.config == null) {
System.out.println("The cachedServiceComponent introduced an observable race!");
System.exit(0);
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}
}