What is an important point to consider while passing an object from one thread to another thread in Java?What are the rules for creating Immutable Objects in Java?
What is an important point to consider while passing an object from one thread to another thread in Java?
This is a multi-threading scenario. In a multi-threading scenario, the most important point is to check whether two threads can update same object at the same time.
If it is possible for two threads to update the same object at the same time, it can cause issues like race condition.
So it is recommended to make the object Immutable. This will help in avoiding any concurrency issues on this object.
What are the rules for creating Immutable Objects in Java?
As per Java specification, following are the rules for creating an Immutable object:
Do not provide "setter" methods that modify fields or objects referred to by fields.
Make all fields final and private.
Do not allow subclasses to override methods.
The simplest way to do this is to declare the class as final.
A more sophisticated approach is to make the constructor private and construct instances in factory methods.
If the instance fields include references to mutable objects, do not allow those objects to be changed.
Do not provide methods that modify the mutable objects.
Do not share references to the mutable objects.
Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies.
Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
Comments
Post a Comment