8

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

1 Answers1

5

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.

Michael
  • 41,989
  • 11
  • 82
  • 128
  • 1
    thank you so much for this answer, I found [this article](https://rules.sonarsource.com/java/tag/java8/RSPEC-3436) this also explain the same thing with an example for all who are new to java 8 like me – Mohammed Housseyn Taleb Jul 10 '19 at 11:51