Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java's TimeZone thread-safe?

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!

like image 517
His Avatar asked Nov 12 '09 23:11

His


People also ask

What is TimeZone getDefault?

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.

What is Java TimeZone?

Java TimeZone class represents a time zone offset, and also figures out daylight savings. It inherits the Object class.

How do I change the default TimeZone in Java?

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.


2 Answers

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.

like image 94
Alexander Pogrebnyak Avatar answered Sep 19 '22 21:09

Alexander Pogrebnyak


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.

like image 22
OscarRyz Avatar answered Sep 20 '22 21:09

OscarRyz