Why you should never use synchronized on Optional java object
Asked Answered
B

1

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

Barker answered 10/7, 2019 at 11:31 Comment(5)
@HadiJ nope, that is not it...Hillie
docs.oracle.com/javase/8/docs/api/java/lang/doc-files/…Revolution
Thanks @Revolution :) now I will read about value-based classes to know more :)Barker
the real answer is hereHillie
@Hillie I also found thisBarker
S
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.

Salado answered 10/7, 2019 at 11:40 Comment(1)
thank you so much for this answer, I found this article this also explain the same thing with an example for all who are new to java 8 like meBarker

© 2022 - 2024 — McMap. All rights reserved.