immutable object concept

 // example immutable object
  public class Dog {
      private String name;
      private Date birthDate;
 
      public Dog(String name, Date birthDate) {
          this.name = name;
          this.birthDate = birthDate;
      }
 
      public String getName() {
          return name;
      }
 
      public Date getBirthDate() {
          // see note below!
          return (Date) birthDate.clone();
      }
  }
Creating immutable objects can be tricky. In the above example, the birthDate field can be modified, so we don't want to return a reference to it. Instead, clone the object and return a copy. This ensures that nobody can modify the Dog instance.

Immutable objects do not prevent you from changing data. You just have to replace the existing object with a new one that has your updated data. One simple approach is to use a manager object (which is thread safe) to create and replace immutable objects. For example:

// This class provides thread-safe methods to add/remove/update dogs.
// An actual implementation may use a relational database as its
// underlying storage mechanism.
public class Kennel {
    public synchronized void create(Dog dog) { ... }
    public synchronized void update(Dog orig, Dog modified) { ... }

can you please advise on immutable objects concept as explained in below link.
http://www.ociweb.com/resources/publications/sett/april-2000tips-for-creating-thread-safe-code-avoiding-race-conditions/
I have not undersood why it is tricky and why
the birthDate field can be modified, so we don't want to return a reference to it. Instead, clone the object and return a copy. This ensures that nobody can modify the Dog instance.
Please advise
LVL 7
gudii9Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gurpsbassiCommented:
the birthDate field can be modified, so we don't want to return a reference to it. Instead, clone the object and return a copy. This ensures that nobody can modify the Dog instance.

birthDate is a Date object. Objects can be modified by reference. Therefore the method returns a clone of it instead (a like for like copy). So anyone making modifications to the returned birthDate object wont disrupt the Dog class by mutating its copy of birthDate.

Personally I would use a Builder pattern instead.
dpearsonCommented:
You should start from the broken code:

public class Dog {
	private String name;
	private Date birthDate;

	public Dog(String name, Date birthDate) {
		this.name = name;
		this.birthDate = birthDate;
	}

	public String getName() {
		return name;
	}

	public Date getBirthDate() {
		return birthDate ;
	}

	@Override
	public String toString() {
		return "Dog{" +
				"name='" + name + '\'' +
				", birthDate=" + birthDate +
				'}';
	}

	public static void main(String[] args) {
		// Let's create a dog with a birthdate of today
		Date today = new Date() ;
		Dog dog = new Dog("Fido", today) ;

		System.out.println("Before: " + dog) ;

		// But now we can get the Date object from the dog
		// and change it - which changes the dog object
		// So 'dog' is not immutable
		Date birthday = dog.getBirthDate() ;
		birthday.setTime(0);

		System.out.println("After:  " + dog) ;

	}
}

Open in new window


Run this and you should get output like this:

Before: Dog{name='Fido', birthDate=Mon Oct 12 14:07:51 PDT 2015}
After:  Dog{name='Fido', birthDate=Wed Dec 31 16:00:00 PST 1969}

which shows that with this code I managed to modify the birthdate of the dog.

If it's immutable, that should be impossible.

If you then modify the code to use the ".clone()" method you'll see it still runs, but it doesn't change the dog's birthdate.

Hope that helps,

Doug

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gudii9Author Commented:
how to add clone method?I am still not clear. please advise
gudii9Author Commented:
package ee;

import java.util.Date;

public class Dog {
	private String name;
	private Date birthDate;

	public Dog(String name, Date birthDate) {
		this.name = name;
		this.birthDate = birthDate;
	}

	public String getName() {
		return name;
	}

	public Date getBirthDate() {
		return birthDate ;
	}

	@Override
	public String toString() {
		return "Dog{" +
				"name='" + name + '\'' +
				", birthDate=" + birthDate +
				'}';
	}
	
	@Override
	public String clone() {
	return null;
	}

	public static void main(String[] args) {
		// Let's create a dog with a birthdate of today
		Date today = new Date() ;
		Dog dog = new Dog("Fido", today) ;

		System.out.println("Before: " + dog) ;

		// But now we can get the Date object from the dog
		// and change it - which changes the dog object
		// So 'dog' is not immutable
		Date birthday = dog.getBirthDate() ;
		birthday.setTime(0);

		System.out.println("After:  " + dog) ;

	}
}

Open in new window


above gave below output
Before: Dog{name='Fido', birthDate=Wed Oct 28 14:49:25 EDT 2015}
After:  Dog{name='Fido', birthDate=Wed Dec 31 19:00:00 EST 1969}


How do i test using the clone method to see how it does not change?
gudii9Author Commented:
http://www.tutorialspoint.com/java/lang/object_clone.htm

I looked at above link but does not explain relating to this scenario of question. please advise.
import java.util.GregorianCalendar;

public class ObjectDemo {

   public static void main(String[] args) {

   // create a gregorian calendar, which is an object
   GregorianCalendar cal = new GregorianCalendar();

   // clone object cal into object y
   GregorianCalendar y = (GregorianCalendar) cal.clone();

   // print both cal and y
   System.out.println("" + cal.getTime());
   System.out.println("" + y.getTime());
   }
}

Open in new window


i do not see any clone method also in above code.

I got below output though which is unchanged

Thu Oct 29 11:17:54 EDT 2015
Thu Oct 29 11:17:54 EDT 2015
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.