Immutable Objects in Java

Reading Time: 3 minutes

Immutability of an object indicates that once an object is constructed with given values, its state and values cannot be altered. In case of any value change must result in new object creation.

Out of box Java offers some Immutable objects for instance java.lang.String, java.lang.Integer, java.lang.Float, java.math.BigDecimal.

Immutable objects make generally a good use in concurrent programming. The reliability is a key aspect in concurrent programming, so that corrupted data sets and objects may cause unwanted behaviors in applications.

Pros

  • Reliable and Atomic Data: The given data during the initialization of the immutable object is always the same, thus the data set is ensured and atomic. Furthermore, An Immutable object can be a good candidate to be the Key in Map collection,
  • Thread Safety/Concurrency: The content of an immutable object is valid and no method may cause an alteration of the state thus it is thread safe,
  • Garbage Collection: The garbage collectors can easily identify and make decisions on immutable objects.

Cons

  • Mass of objects: Allocating lots of new objects may cause to increase the memory allocation for modifications. This can be somehow manageable while employing a good model of java memory management.

Rules to define an Immutable Object:
Immutability of an object indicates that once an object is constructed with given values, its state and values cannot be altered. In case of any value change must result in new object creation.
Out of box Java offers some Immutable objects for instance java.lang.String, java.lang.Integer, java.lang.Float, java.math.BigDecimal.
Immutable objects make generally a good use in concurrent programming. The reliability is a key aspect in concurrent programming, so that corrupted data sets and objects may cause unwanted behaviors in applications.

Pros:
-Reliable and Atomic Data: The given data during the initialization of the immutable object is always the same, thus the data set is ensured and atomic. Furthermore, An Immutable object can be a good candidate to be the Key in Map collection,
-Thread Safety/Concurrency: The content of an immutable object is valid and no method may cause an alteration of the state thus it is thread safe,
-Garbage Collection: The garbage collectors can easily identify and make decisions on immutable objects,

Cons:
-Allocating lots of new objects may cause to increase the memory allocation for modifications. This can be somehow manageable while employing a good model of java memory management.

Rules to define an Immutable Object

1. Mark the designated immutable class as final; this will disallow the class to be subclasses or its methods to be overridden,
2. Mark all the fields with the final keyword and package access as private, this way fields will not be discoverable for other classes, as well as the values of fields will be forced to be initially set,
3. Mark the no arg constructor as private thus; creation of an empty valued object will be prevented,
4. Provide only one constructor and mark it as public to force callers to initialize all the fields,
5. Elimination of any methods that may change the state known as Setter Methods,
6. Last of all in case of having a mutable class as field member;
a. Mark it as final, so that its value can be assigned once only,
b. Disallow to have methods that will change the object state,
c. Perform to clone of the object not the object reference via getter methods, thus the alteration will be prevented.

Sample Immutable Object

import java.util.Collections;
import java.util.Date;
import java.util.List;

//Rule #1
public final class Student {
    /**
     * Immutable Object Field Declarations
     */
  //Rule #2
    private final String name;
    private final String lastName;
  //Rule #6a
    private final Date birthDate;
    private final List<String> classes;

    /**
     * Immutable Object Constructor Declarations
     */
  //Rule #3
    private Student() {
        this(null, null, null, null);
    }

  //Rule #4
    public Student(String name, String lastName, Date birthDate, List<String> classes) {
        this.name = name;
        this.lastName = lastName;
        this.birthDate = birthDate;
        this.classes = classes;
    }
  
  //Rule #5 and #6b- No setter methods exist

    /**
     * Immutable Object Getter Method Declarations
     */
    public String getName() {
        return name;
    }

    public String getLastName() {
        return lastName;
    }

  // Rule #6c
    public Date getBirthDate() {
        return (Date) birthDate.clone();
    }

    public List getClasses() {
        return Collections.unmodifiableList(classes);
    }
}

 

Installing Oracle Java on Ubuntu and Fedora

Reading Time: 1 minute

Description

In this article we will install Oracle’s Java, besides the OpenJDK can be shipped with the package managers in the distros. This way will allow you to end-to-end fully install Oracle JDK. The version I used was against version 8, but you can also use the same way for the other versions as well

Specifications

Ubuntu 18.04 LTS 64 Bit

Oracle Java 8 Update 181

Steps

1. Download the Java from the Oracle’s web site

2. Unpack the tar file

tar zxvf jdk-8u181-linux-x64.tar.gz

3. Create a folder in the usr location

sudo mkdir /usr/java

4. Move all the files from the unzipped location to the newly created folder

sudo mv jdk1.8.0_181/ /usr/java

5. Install all the java commands using the alternatives

sudo update-alternatives --install "/usr/bin/java" "java" "/usr/java/jdk1.8.0_181/bin/java" 1
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/java/jdk1.8.0_181/bin/javac" 1
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/java/jdk1.8.0_181/bin/javaws" 1
sudo update-alternatives --install /usr/bin/jar "jar" "/usr/java/jdk1.8.0_181/bin/jar" 1

6. Fix the permissions for the Java entries

sudo chmod a+x /usr/bin/java 
sudo chmod a+x /usr/bin/javac 
sudo chmod a+x /usr/bin/javaws
sudo chmod a+x /usr/bin/jar
sudo chown -R root:root /usr/java/jdk1.8.0_181

7. Add Java home to the Global Environment

sudo nano /etc/environment

7.1. And add the below line and save

JAVA_HOME=/usr/java/jdk1.8.0_172
JRE_HOME=$JAVA_HOME/jre
PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
export JAVA_HOME
export PATH

8. Reflect the Global Environment changes

source /etc/environment
. /etc/environment

9. Check the installation for Java

java -version
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)

10. Check the installation for Java Compiler

javac -version
javac 1.8.0_181

11. Check the installation for Java Web Start

javaws -version
Java(TM) Web Start 11.181.2.13-fcs

11. Check the installation for Jar

jar
Usage: jar {ctxui}[vfmn0PMe] [jar-file] [manifest-file] [entry-point] [-C dir] files ...
sudo update-alternatives --config java
sudo update-alternatives --config javac
sudo update-alternatives --config javaws
sudo update-alternatives --config jar