I wanted my application to just have one TimeZone
object which will be used by many SimpleDateFormat
and Calendar
objects from the other places concurrently. This is to avoid having to always do TimeZone.getTimeZone(ID)
.
I know SimpleDateFormat
and Calendar
classes are not thread safe, which is why I configure one thread to always create new instances of them. But what about TimeZone
? It is not clear to me whether I can do the following safely:
final TimeZone tz = TimeZone.getTimeZone("GMT");
...
//Thread 1.
Thread t1 = new Thread(Runnable(){
public void run()
{
Calendar cal = Calendar.getInstance(tz);
...
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(tz);
...
}
});
t1.start();
...
//Thread 2.
Thread t2 = new Thread(Runnable(){
public void run()
{
Calendar cal = Calendar.getInstance(tz);
...
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(tz);
...
}
});
t2.start();
...
Thanks!
Typically, you get a TimeZone using getDefault which creates a TimeZone based on the time zone where the program is running. For example, for a program running in Japan, getDefault creates a TimeZone object based on Japanese Standard Time. You can also get a TimeZone using getTimeZone along with a time zone ID.
Java TimeZone class represents a time zone offset, and also figures out daylight savings. It inherits the Object class.
You can explicitly set a default time zone on the command line by using the Java system property called user. timezone . This bypasses the settings in the Windows operating system and can be a workaround.
I looked once at the source code for it and came to a conclusion that it was not.
Look at JodaTime timezone class. It says in javadoc that it's thread-safe and immutable.
It is not.
And you don't need it. You code uses it as:
final TimeZone tz = TimeZone.getTimeZone("GMT");
......
// thread 1 SimpleDateFormat instance
sdf.setTimeZone(tz);
// thread 2 SimpleDateFormat instance
sdf.setTimeZone(tz);
You have two threads using the same time zone, but since you are not modifying it you don't need it to be thread safe.
The only thing that you can modify is the ID, but even then you're ok, for the rest of the attributes are read-only
The only way you can get into trouble is by changing the id and caching your self the timezone, if you get it always from the TimeZone.getTimeZone()
you are safe too, because that method is thread safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With