Using immutable objects when possible

When you develop an application in Java using object-oriented programming, you create some classes formed by attributes and methods. The methods of a class determine the operations that you can do with the class. Attributes store the data that defines the object. Normally, in each class, you implement some methods to establish the value of the attributes. Also, objects change as the application runs, and you use those methods to change the value of their attributes.

When you develop a concurrent application, you have to pay special attention to the objects shared by more than one thread. You must use a synchronization mechanism to protect access to such objects. If you don't use it, you may have data inconsistency problems in your application.

There are special kinds of objects that you can implement when you work with concurrent applications. They are called immutable objects; their main characteristic is that they can't be modified after they are created. If you need to change an immutable object, you must create a new one instead of changing the values of the attributes of the object.

This mechanism presents the following advantages when you use them in concurrent applications:

  • These objects cannot be modified by any thread once they are created, so you won't need to use any synchronization mechanism to protect access to their attributes.
  • You won't have any data inconsistency problems. As the attributes of these objects cannot be modified, you will always have access to a coherent copy of the data.

The only drawback of this approach is the overhead: creating new objects instead of modifying existing ones.

Java provides some immutable classes, such as the String class. When you have a String object and you try to assign a new value to it, you are creating a new String object instead of modifying the old value of the object. For example, check out the following code:

    String var = "hello"; 
var = "new";

In the second line, JVM creates a new String object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.27.72