Why you should never use synchronized on Optional java object

Mohammed Housseyn Taleb :

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 ???

Michael :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=120667&siteId=1