Google

May 14, 2014

How to make a Java class immutable tutorial?

Q. What are immutable objects?
A. These are objects that cannot be modified once created.

Q. Why is it a best practice to make your classes immutable where applicable?
A.
  • Immutable objects are inherently thread-safe and can be shared between threads. 
  • Immutable objects are good candidates for map keys and set elements as the values cannot be modified once added.
  • Immutable objects are easier to construct, test, and use. 
  • Immutable objects will always be in a deterministic state, even when an exception is thrown.
 Q. What are the guidelines to make a class immutable?
 A.
  • make all fields private and final.
  • don't provide any setter methods
  • don't allow sub classes to override methods by making the class final.
  • make sure that the other objects used are immutable as well. Defensively copy those objects.
In Java API, the String class and the wrapper classes like Integer, Double, Character, etc are immutable objects. Let's look at different examples to make a class immutable like builder pattern, etc.


Example 1: basic scenario

Immutable Person class

import java.util.Date;

public final class Person {
 private final Date birthDate;

 public Person(Date birthDate) {
  //defensively copy
  this.birthDate = new Date(birthDate.getTime());
 }

 public Date getBirthDate() {
  return new Date(birthDate.getTime()); //defensively copy
 }
        
 @Override
 public String toString() {
    return "Person [birthDate=" + birthDate + "]";
 }   
}

The test class

import java.util.Calendar;
import java.util.Date;

public class PersonTest {
 
 public static void main(String[] args) {
  
  Calendar cal = Calendar.getInstance();
  cal.set(1990,01,01,00,00,00);
  Date birthDate = cal.getTime();
  
  Person person = new Person(birthDate);
  System.out.println(person);
  
  //if you did not defensively copy
  //remember java is pass by reference
  //mutating the birthDate will change person's dateOfBirth
  birthDate.setTime(new Date().getTime());
  
  System.out.println(person);
  
 }
}

Output will be

Person [birthDate=Thu Feb 01 00:00:00 EST 1990]
Person [birthDate=Thu Feb 01 00:00:00 EST 1990]

So, the above Person is an immutable class.

a) no setter method to mutate the  birthDate.
b) the passed in  in the constructor is birthDate is defensively copied, and not used directly.
c) The class itself is final. If it's not final then anyone could extend the class and do whatever they like, like providing setters, shadowing your private variables, and basically making it mutable.

Q. Why should we defensively copy the date in the constructor and the getter method?
A. If the reference escapes from the constructor or getter method, it can be mutated from outside as shown below since unlike a String object, the Date itself a mutable class with setter methods like setTime, setMonth, etc.

If you remove defensive copying in the constructor as shown below
import java.util.Date;

public final class Person {
 private final Date birthDate;

 public Person(Date birthDate) {
  this.birthDate = birthDate;
 }

 public Date getBirthDate() {
  return birthDate;
 }

 @Override
 public String toString() {
  return "Person [birthDate=" + birthDate + "]";
 } 
}


Now, rerun the PersonTest, and you will now get

Person [birthDate=Thu Feb 01 00:00:00 EST 1990]
Person [birthDate=Tue May 13 23:10:24 EST 2014]

The person's birthDate has been mutated.


Example 2: using the builder design pattern

It is more elegant to create immutable objects using the builder design pattern as shown below.

import java.util.Date;

public final class Person {
 private final Date birthDate;

 private Person(Builder builder) {
  this.birthDate = builder.birthDate;
 }
 
 public Date getBirthDate() {
  return new Date(birthDate.getTime());
 }

 @Override
 public String toString() {
  return "Person [birthDate=" + birthDate + "]";
 }

 // builder design pattern. static inner class
 public static class Builder {
  private Date birthDate;

  public Builder birthDate(Date birthDate) {
   this.birthDate = new Date(birthDate.getTime());
   return this;
  }

  public Person build() {
   return new Person(this);
  }
 }
}


The test class

import java.util.Calendar;
import java.util.Date;

public class PersonTest {

 public static void main(String[] args) {

  Calendar cal = Calendar.getInstance();
  cal.set(1990, 01, 01, 00, 00, 00);
  Date birthDate = cal.getTime();

  Person person1 = new Person.Builder().birthDate(birthDate).build();
  System.out.println(person1);
 }
}



Example 3: copy write methods

If you want to get adjusted date of birth without mutating the Person, you can copy the fields and then mutate it. Make sure that the internal birthDate does not escape.

  
public Date getAdjustedBirthYear(int years) {
  Calendar cal = Calendar.getInstance();
  cal.setTime(birthDate);  
  cal.add( Calendar.YEAR, years );  
  return  cal.getTime(); //new Date object
}




Q. What is the difference between "final" and "const" keywords in Java?
A. final on a reference variable just means that the reference cannot be changed, but the actual object values can be changed if they are not immutable. "const is a reserved keyword" in Java but not used yet. const in C++ means that you actually cannot change the object itself (by calling the mutator methods)


Q. What if the Person class had a collection of children as in List<child> as an attribute?
A. Firstly, you need to deeply clone them and make sure that the children reference is immutable so that new elements cannot be added or removed.


Collections.unmodifiableList(children); //only prevents addition & removal of elements


Secondly, you need to deeply copy each element so that they cannot be modified.

public static List<Child> deepCopy(List<Child> childList) {
    List<Child> clonedList = new ArrayList<Child>(childList.size());
    for (Child child : childList) {
        clonedList.add(new Child(child));
    }
    return clonedList;
}

Alternatively, use the Google's Gauva library to create immutable collections

public static final ImmutableSet<String> COLOR_NAMES = ImmutableSet.of(
  "red",
  "orange",
 );


Labels: ,

Jan 23, 2014

Setting up Java and Maven with environment variables

This is an extension post to Java Tutorial: Setting up Java, Maven, and eclipse. Setting up Java and Maven is the first step any beginner has to do. So, understanding this will save so much pain.

Q. What are environment variables?
A. An environment variable defines some aspect of a user's or a program's environment. After you have installed the Java Runtime Environment (JRE) in Windows, you must set the JAVA_HOME environment variable to point to the JRE installation directory. Same applies for other applications like Maven. These variables are then used to set the "PATH" variable so that when you type "java" or "mvn" on a dos command line, the application can be found.

In a Windows platform, you can write a batch file to set up your environment variables as shown below:

@echo off
REM This is sample to set up your Java and Maven environment variables
SET TOOLS_HOME=C:\tools
SET USERPROFILE=%TOOLS_HOME%\home
SET JAVA_HOME=%TOOLS_HOME%\java\jdk1.6.0_45
SET M3_HOME=%TOOLS_HOME%\maven\apache-maven-3.1.0
SET MAVEN_OPTS=-Xmx512m -Duser.home=%USERPROFILE%

SET PATH=%PATH%;%M3_HOME%\bin;%JAVA_HOME%\bin


echo ******** Java Toolkit setup ****************
echo USERPROFILE = %USERPROFILE%
echo JAVA_HOME   = %JAVA_HOME%
echo M3_HOME     = %M3_HOME%
echo PATH        = %PATH%
echo ********************************************


Q. How do you list the environment variables on DOS command prompt?
A. by typing the "set" command.

Q. How do echo a particular variable?
A. by typing the "echo %M3_HOME%" command display M3_HOME variable. In Unix use echo $M3_HOME. You can also do "set path" to display the program path or "set M3_HOME" to display maven env variable.

Q. How will you set your environment variables on an account or System level on Windows 8 or later?
A. On Windows 8, search for "Edit environment variables".



Then, you can set it via the pop up GUI



Q. Maven needs a settings.xml file. How do you find out which settings.xml file is used by Maven?
A. With the debug option mvn -X command.

[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from C:\TOOLS\maven\apache-maven-3.1.0\bin\..\conf\settings.xml
[DEBUG] Reading user settings from C:\Users\akumaras\.m2\settings.xml
[DEBUG] Using local repository at c:\tools\home\.m2\repository
[DEBUG] Using manager EnhancedLocalRepositoryManager with priority 10.0 for c:\tools\home\.m2\repository

You can get both the settings.xml file and the repository location "c:\tools\home\.m2\repository" where the artefacts will be downloaded to.




Maven uses the user.home property set via MAVEN_OPTS

SET MAVEN_OPTS=-Xmx512m -Duser.home=%USERPROFILE%

Q. How do you know that your Java and Maven are set up correctly?
A.Typing Java or MVN on a command prompt should recognize the command and give you an appropriate display with its version numbers, etc.

Q. How does maven know where to download the jar files from? in other words, how do you specify the Maven repository location?
A. Following snippets in the settings. xml file. The repo location is http://search.maven.org/

<profiles>
    <profile>
      <id>JDK</id>
      <activation>
        <property>
          <name>JDK</name>
        </property>
      </activation>
      <properties>
        <JDK_1_5>c:\tools\java\jdk-1.5.0_06</JDK_1_5>
        <JDK_1_6>c:\tools\java\jdk-1.6.0_11</JDK_1_6>
      </properties>

    </profile>
    
 <profile>
  <id>nexus</id>
  <activation>
   <activeByDefault>true</activeByDefault>
  </activation>
  <!--Enable snapshots for the built in central repo to direct -->
  <!--all requests to nexus via the mirror -->
  <repositories>
   <repository>
    <id>central</id>
    <url>http://search.maven.org/</url>
    <releases><enabled>true</enabled></releases>
    <snapshots><enabled>true</enabled></snapshots>
   </repository>
  </repositories>
  <pluginRepositories>
   <pluginRepository>
    <id>central</id>
    <url>http://search.maven.org/</url>
    <releases><enabled>true</enabled></releases>
    <snapshots><enabled>false</enabled></snapshots>
   </pluginRepository>
  </pluginRepositories>
 </profile>
</profiles>

Q. If I already have the jar file, can I manually install into my Maven repository pointed by user.home property as demonstrated above?
A. Yes, use the following command

mvn install:install-file \
  -DgroupId=org.springframework \
  -DartifactId=spring-core \
  -Dpackaging=jar \
  -Dversion=3.1.0.RELEASE \
  -Dfile=jta-1.0.1B.jar \
  -DgeneratePom=true
 
Q. How do you search for artifacts on the central repository?
A. Go to central repository website http://search.maven.org/ and search. Prefix with g: for groupid, a: for artifactid, and v: for version number.

g:org.springframework a:spring-core  v:3.1.0.RELEASE


You may also like



Labels: ,

Sep 21, 2012

Java Tutorial: Setting up Java, Maven, and eclipse

This is mainly for the beginners of Java to get familiarized with Java, Maven, and eclipse. This will also be handy for starting on your self-taught Java projects.

Install and configure Java

Step 1:  Download and install Java 6 or later version if available by googling "Java downloads". Make sure that you download and install the right version for the operating system on which you will be running -- for example Windows (32 bit or 64 bit), Linux, Solaris, MAC, etc. You will need both the JDK and the JRE.




The javac is the compiler that converts a source file (e.g. HelloWorld.java) to a byte code file  (e.g. HelloWorld.class). The java is the run-time command to execute a program (i.e. java HelloWorld). The src.zip is where all the library files are located and rt.jar is where the run-time class files are located.

Step 2: Set the environment variables. In a command prompt, if you type "set" (in WIN 32)  and "env" (in Unix), it will show all the environment variables. You need to set the JAVA_HOME environment variable. In DOS it is %JAVA_HOME% and in a Unix system, it is $JAVA_HOME. You also need to add %JAVA_HOME%/bin to the "path" environment variable. you can verify if Java is set up correctly by typing the following command in a command prompt.



If the version is not displayed, then Java is not set up correctly.

Install and configure Maven

Maven is a build and deployment tool.

Step 1: Download and install Maven from http://maven.apache.org/download.html.

Step 2: Configure the environment variables "M2_HOME" and "path". Use M2_HOME instead of M3_HOME as eclipse might not work well with M3_HOME. For example

SET USERPROFILE=%TOOLS_HOME%home
SET JAVA_HOME=%TOOLS_HOME%java\jdk-1.6.0_25

SET M2_HOME=%TOOLS_HOME%maven\apache-maven-3.0.3

SET MAVEN_OPTS=-Xmx512m -XX:MaxPermSize=256m -Duser.home=%USERPROFILE%

Once maven has been set up correctly, you should be able to verify it by


You can set up the repository location by opening the settings.xml file under conf folder inside your maven installation directory. Repository is where the dependency Java libraries will be stored.

<localRepository>c:\tools\home\.m2\repository</localRepository>

If your internet access requires proxy settings, you need have that added to your settings.xml file.

<proxy>

  <id>optional</id>

  <active>true</active>

  <protocol>http</protocol>

  <username>proxyuser</username>

  <password>proxypass</password>

  <host>webproxy</host>

  <port>8080</port>

  <nonProxyHosts>local.net,some.host.com</nonProxyHosts>

</proxy>


Install and configure eclipse. 

Step 1: Download and install eclipse latest version from http://www.eclipse.org/downloads/. It is an IDE (i.e. Integrated Development Environment). Get the EE (Enterprise Edition).



Step 2: It is a good practice to keep your eclipse work space separate from where your tutorials or projects are stored. This will not tie up your projects or tutorials with an IDE. What if you want to use your projects or tutorials with NetBeans? For example


Here is a simple step by step guide in setting up Maven and eclipse

Step 1: The settings.xml file under %M2_HOME%/conf is where you can set up your local repository location, central repository server from where you can download the relevant artifacts, proxy server settings to access internet, etc as shown below.

<?xml version="1.0" encoding="UTF-8"?>

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  
  <localRepository>c:\temp\java\.m2\repository</localRepository>
  
  <proxies>    
    <proxy>
   <id>genproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>username</username>
      <password>passwd</password>
      <host>proxy-server</host>
      <port>8080</port>
      <nonProxyHosts>localhost</nonProxyHosts>
    </proxy>
  
  </proxies>
  
 
</settings>


You can browse the repository by going to http://search.maven.org where you can search for artifacts and relevant version numbers. You can even manually download artifacts.

Need to add the following snippets to the root element of your settings.xml file to tell where to download the jar files from.
<profiles>
    <profile>
      <id>JDK</id>
      <activation>
        <property>
          <name>JDK</name>
        </property>
      </activation>
      <properties>
        <JDK_1_5>c:\tools\java\jdk-1.5.0_06</JDK_1_5>
        <JDK_1_6>c:\tools\java\jdk-1.6.0_11</JDK_1_6>
      </properties>

    </profile>
    
 <profile>
  <id>nexus</id>
  <activation>
   <activeByDefault>true</activeByDefault>
  </activation>
  <!--Enable snapshots for the built in central repo to direct -->
  <!--all requests to nexus via the mirror -->
  <repositories>
   <repository>
    <id>central</id>
    <url>http://search.maven.org/</url>
    <releases><enabled>true</enabled></releases>
    <snapshots><enabled>true</enabled></snapshots>
   </repository>
  </repositories>
  <pluginRepositories>
   <pluginRepository>
    <id>central</id>
    <url>http://search.maven.org/</url>
    <releases><enabled>true</enabled></releases>
    <snapshots><enabled>false</enabled></snapshots>
   </pluginRepository>
  </pluginRepositories>
 </profile>
</profiles>


Note: Drill down by groupid that specify in your pom.xml file under dependencies.
Step 2: Generate the pom structure with the following maven command.

C:\Temp\Java\projects>mvn archetype:generate -DgroupId=com.mytutorial -DartifactId=simple

Note: Make sure that you already don't have a folder "simple" under projects. Accept the default settings when prompted by pressing enter. Now, if you inspect the file structure, it will look like.


Carefully, inspect the folders and files that maven has created. The local repository will also have a number of jar files for project dependencies like junit.jar and maven plugin jars.



This maven project can be imported into eclipse.

Step 3: create an eclipse short cut as shown below to open eclipse with your workspace "my-tutorials"

C:\Tools\eclipse\eclipse-3.7-SR2-win32-x86_64\eclipse.exe -data  C:\Temp\Java\workspace\my-tutorials


Step 4: Close the welcome splash screen, and tell eclipse with the help of the m2e (i.e maven to eclipse) plugin where your maven settings.xml file is residing. This is done by selecting from the eclipse main menu Window --> Preferences --> Maven (note: you can also search at the top in the Preferences dialogue).  As you can see below, it will also display your repository location as highlighted in blue.



Now, you can refresh your projects or select the project "simple" and then right-mouse-click to bring up the contextual menu, and then select "Maven --> Update Dependencies" to see the packages your project depends on. In this example, it is junit-xxx.jar.




You can also check you build path by  right-mouse-clicking on the simple project and then selecting Build Path --> Configure Build Path

Step 5: Import the maven project you had just created. Select  File --> Import and then



Click Next,



Step 6: Now, you can see the "App.java" Java source file as shown below. This was created by Maven.



Also inspect the pom.xml file which is used for packaging up your artifacts. The junit.jar is required for writing unit tests. You can also notice AppTest.java under src/test/java 




Step 7: You can run the class by "right-clicking" on App.java to bring up the contextual menu and then selecting "Run As" and then "Java Application", which prints the output "Hello World" in the console tab window.


Step 8: You can now package it as a jar file by running the mvn command on a command prompt. The pom file says the packaging type is "jar". Currently the target folder is empty, and once you package it, it will have the packaged artifacts.

Firstly, locate the folder where the pom.xml file is and then execute the mvn command.


The command is "mvn clean package". if you refresh the "target" folder by selecting it and pressing F5 or by selecting it and then right-mouse-clicking and then selecting "Refresh" you will see the artifacts that are generated. If you don't want the junit tests to be run, you can add -Dmaven.test.skip to the above command.

If you want the package to be deployed to your maven repository which is located at "c:\temp\java\.m2\repository" you should run the command "mvn clean install".



Step 9: Finally, you can run the jar file from a command prompt.The classpath tells where to find the App.class file.




java -classpath C:\Temp\Java\.m2\repository\com\mytutorial\simple\1.0-SNAPSHOT\simple-1.0-SNAPSHOT.jar com.mytutorial.App 


That's it. You now have Java, Maven (build tool), and eclipse (IDE) working with each other. If you liked this give me your feedback and stay tuned for more tutorials.

Note: If you want to generate the eclipse related artifacts outside eclipse from a command-line, you can issue the following command mvn eclipse:clean eclipse:eclipse. Similar commands are available for other IDEs as well.

You may also like


Labels: , ,