Alex Rivera | Logout

Is Java's TimeZone thread-safe?

Asked 2009-11-12T23:38:03.580
19

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!

Edit
Report

1 Answer

1

You are not modifying your TimeZone, so your code should be thread safe regardless of whether the underlying implementation of TimeZone is thread safe (with the exception of static methods, like (getTimeZone/getDefault/setDefault).

answered 2009-11-13T00:02:16.480

Your Answer