2

Should org.joda.time.DateTimeZone be defined as static in a class instead of creating a new instance each time it's needed, specially when we're always using the same time zone.

DateTimeZone is thread-safe and immutable so it does not make sense to create a new instance each time. Is my thinking correct?

To add more details, currently my class creates a DateTimeZone object in the constructor of my class, always for the same time zone, so I thought why not make it static instead of creating a new object each time.

Learner
  • 1,503
  • 6
  • 23
  • 44

2 Answers2

3

DateTimeZone is thread-safe and immutable, and all subclasses must be as well.

See api

So yes. It can be declared as static field.

Should you do it or not, it depends on your class and overall project design. See here why static fields may be evil.

Mike Adamenko
  • 2,944
  • 1
  • 15
  • 28
1

Yes, I think you can create is as a static field - and the link in @Mike's answer tells you about the possible drawbacks of doing so (like possible problems if you want to test your code in a different timezone and so on).

But if your concerns are about performance and memory usage, I wouldn't worry too much about that. It seems that Joda-Time uses an internal cache of DateTimeZone objects:

DateTimeZone zone = DateTimeZone.forID("Europe/London");
DateTimeZone other = DateTimeZone.forID("Europe/London");
System.out.println(zone == other); // true

The code above prints true, which means that both are the same object.

Of course this is an implementation detail (I'm using Joda-Time 2.9.9) and it's not good to rely on such details as these things can change.

Anyway, if you're sure that this timezone will never change, you can make it static. If there's a possibility of having more than one in the future, don't (I wouldn't).