Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of annotating an immutable Java class with @Immutable?

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?

like image 431
Kkkev Avatar asked Nov 24 '14 09:11

Kkkev


People also ask

What is the advantage of immutable class in Java?

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.

What are the advantages of annotations in Java?

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.

Which of the following statements are correct advantages of an immutable class?

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.

What are the advantages & disadvantages of immutable?

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.


1 Answers

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.

like image 116
assylias Avatar answered Oct 14 '22 07:10

assylias