Skip to main content

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?

 

Photo by Christina Morillo from Pexels

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

Popular posts from this blog

AirBnB Infographic Journey to IPO

  Full Post at  https://techpomelo.com/2020/10/infographics-airbnb-milestone-journey-to-ipo/

Defination of the essential properties of operating systems

Define the essential properties of the following types of operating sys-tems:  Batch  Interactive  Time sharing  Real time  Network  Parallel  Distributed  Clustered  Handheld ANSWERS: a. Batch processing:-   Jobs with similar needs are batched together and run through the computer as a group by an operator or automatic job sequencer. Performance is increased by attempting to keep CPU and I/O devices busy at all times through buffering, off-line operation, spooling, and multi-programming. Batch is good for executing large jobs that need little interaction; it can be submitted and picked up later. b. Interactive System:-   This system is composed of many short transactions where the results of the next transaction may be unpredictable. Response time needs to be short (seconds) since the user submits and waits for the result. c. Time sharing:-   This systems uses CPU scheduling and multipro-gramming to provide econ...