0

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());
    }
}


3
  • Could you show more code? What you've shown is where you think the problem lies. However that may not be the case and furthermore, even if it turned out to be, there is no context to form an answer. Commented Jan 17, 2020 at 23:14
  • That code cannot throw ConcurrentModificationException. --- Besides, that code is really badly flawed: ofNullable(myObject) means that myObject can be null, and by it's very nature, that orElse(...) can never be effectual, because can only have an effect when myObject is null, which would make myObject.ofDefaults() throw a NullPointerException. Unless of course ofDefaults() is a static method, in which case the code should have been MyObject.ofDefaults(), using the class, not the instance, to qualify the method call, i.e. the code is flawed. Commented Jan 17, 2020 at 23:27
  • @Andreas Sorry, that was a mistake . I corrected the post Commented Jan 17, 2020 at 23:42

1 Answer 1

2

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());
        }
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.