I have several tests that run in parallel, and uses the method below. Please see the code below it throws ConcurrentModificationException occasionally. I cannot figure out how it can happen?
private static MyObject myObject;
public void setupMyObject{
syncronized(this){
myObject = Optional.ofNullable(myObject).orElse(SomeConfig.ofDefaults());
}
}
myObject
is a static variable, to lock it you need to put class object in synchronized. Your present implementation doesn't lock it properly.
import java.util.Optional;
public class Test {
private static String myObject;
public void setupMyObject(){
synchronized(Test.class){
myObject = Optional.ofNullable(myObject).orElse(SomeConfig.ofDefaults());
}
}
}