I get the concept of immutability, and why it is a good idea to make DTOs immutable.
I also notice that Java has an @Immutable
annotation that we can use to annotate immutable classes.
My question is: what does annotating a Java class as @Immutable
give us? Are there any library features that only work on classes annotated in this way?
Benefits of Immutable Class in Java An immutable class is good for caching purposes because you don't have to worry about the value changes. Another benefit of immutable class is that it is inherently thread-safe, so you don't have to worry about thread safety in case of multi-threaded environment.
The benefits of type annotations and example use cases For instance, they can produce informational messages for the developer at compile time, detecting errors or suppressing warnings. In addition, annotations can be processed to generate Java source files or resources that can be used to modify annotated code.
Q5) What are the advantages of immutability? Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided. Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
An immutable object remains in exactly one state, the state in which it was created. Therefore, immutable object is thread-safe so there is no synchronization issue. They cannot be corrupted by multiple threads accessing them concurrently. This is far and away the easiest approach to achieving thread safety.
The annotation documents the fact that your class is immutable and tells the users of the class that you have followed the contract defined in the annotation javadoc. It is also frequent to simply include a comment directly in the javadoc: this is the approach chosen by the JDK, see for example the javadoc of LocalDate.
Some static analysis tools such as FindBugs can also use that annotation and verify that the class really is immutable. If you forgot to make a public field final for example, FindBugs will emit a warning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With