Search code examples
javajava-8option-typesynchronizeddesign-principles

Why you should never use synchronized on Optional java object


I m learning about java optional wrapper, to do so I m reading the following tutorial

however I have a simple question that is not answered in the article: in item 25: Avoid Using Identity-Sensitive Operations on Optionals they are mentioning to NEVER use an optional object in a synchronized way like this:

Optional<Product> product = Optional.of(new Product());

synchronized(product) {

    ...

}

but there is no explanation why, so please would any one here explain to me why this is a bad practice ???


Solution

  • Because

    [value-based classes] are freely substitutable when equal, meaning that interchanging any two instances x and y that are equal according to equals() in any computation or method invocation should produce no visible change in behavior"

    Source (Oracle)

    You can not freely substitute X and Y if there is an intrinsic lock on one of them, since doing so may produce a change in behaviour.