Concurrent Programming Fundamentals — Sharing Objects (Part 3)

Creating an Immutable Object

Don’t add any setter method

Declare all fields final and private

public class DateContainer {
private final Date date;
public DateContainer() {
this.date = new Date();
}
public Date getDate() {
return date;
}
}
.... DateContainer dateContainer = new DateContainer();
System.out.println(dateContainer.getDate());
dateContainer.getDate().setTime(dateContainer.getDate().getTime() + 1000);
System.out.println(dateContainer.getDate());

If a field is a mutable object create defensive copies of it for getter methods

public class DateContainer {
private final Date date;
public DateContainer() {
this.date = new Date();
}
public Date getDate() {
return new Date(date.getTime());
}
}
.... DateContainer dateContainer = new DateContainer();
System.out.println(dateContainer.getDate());
dateContainer.getDate().setTime(dateContainer.getDate().getTime() + 1000);
System.out.println(dateContainer.getDate());

If a mutable object passed to the constructor must be assigned to a field create a defensive copy of it

public class DateContainer {
private final Date date;
public DateContainer(Date date) {
this.date = date;
}
public Date getDate() {
return new Date(date.getTime());
}
}
.... Date date = new Date();
DateContainer dateContainer = new DateContainer(date);
System.out.println(dateContainer.getDate());
date.setTime(date.getTime() + 1000);
System.out.println(dateContainer.getDate());
public class DateContainer {
private final Date date;
public DateContainer(Date date) {
this.date = new Date(date.getTime());
}
public Date getDate() {
return new Date(date.getTime());
}
}
.... Date date = new Date();
DateContainer dateContainer = new DateContainer(date);
System.out.println(dateContainer.getDate());
date.setTime(date.getTime() + 1000);
System.out.println(dateContainer.getDate());

Don’t allow sub-classes to override methods

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store