0

I am just wondering what would be the correct method of making the code below immutable.

Date d = new Date();
Scheduler.scheduleTask(task1, d);
d.setTime(d.getTime() + ONE_DAY);
Scheduler.scheduleTask(task2, d);
Michael
  • 41,989
  • 11
  • 82
  • 128
GreenCoder
  • 15
  • 1
  • 6
  • What does 'immutable code' mean? Do you mean making a `Date` instance immutable? – hunminpark May 04 '17 at 10:28
  • Yes. Date is by nature Mutable isn't it? so how could the code above be made immutable. Is it possible – GreenCoder May 04 '17 at 10:29
  • A Date instance yes – GreenCoder May 04 '17 at 10:30
  • @GreenCoder Your question is unclear: a bit of code is not mutable or Immutable - a class can be. What are you trying to achieve and why do you want immutability? – assylias May 04 '17 at 10:32
  • It's just a question I have here. Examine the code and outline in detail a potential issue that might exist and suggest a solution. – GreenCoder May 04 '17 at 10:33
  • So I am wondering what could I change with the above code to make it safer. – GreenCoder May 04 '17 at 10:34
  • @GreenCoder How about creating your own class (ex. `ImmutableDate`) by wrapping `Date`? For example, we may hold `Date` instance as a `final private` member (ex. `dateValue`) of `ImmutableDate`, and initialize `dateValue` in the constructor `ImmutableDate(year, month, day, ...)`. Don't provide any setter methods, than we may be able to say that an `ImmutableDate` instnace is immutable. (See https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html) – hunminpark May 04 '17 at 10:35
  • Yes I understand you now @hunminpark. I just make a class that follows the Immutable class guidlines and instantiate it within that. – GreenCoder May 04 '17 at 10:37

2 Answers2

1

You can't make that immutable. Immutability is a property of an object. It says that, once instantiated, an object's internal state does not change.

The java.util.Date class, for whatever reason, was not designed to be immutable. This is illustrated nicely by the ability to change the value it contains:

d.setTime(d.getTime() + ONE_DAY);

If you wanted to change your code so that it was not mutating this object, you could do something like:

Date firstDate = new Date();
Scheduler.scheduleTask(task1, firstDate);
Date secondDate = new Date(firstDate.getTime() + ONE_DAY);
Scheduler.scheduleTask(task2, secondDate);

If you can avoid it, do not use java.util.Date. There was a new Date/Time API added in Java 8 located in java.time. The classes located in there are immutable and are often better choices.

Michael
  • 41,989
  • 11
  • 82
  • 128
0

Date object implements clone method, so you can clone your date (d) object instead of making references. In your example would be like this:

Date d = new Date();
Scheduler.scheduleTask(task1, (Date) d.clone());
d.setTime(d.getTime() + ONE_DAY);
Scheduler.scheduleTask(task2, (Date) d.clone());