views:

91

answers:

4

Hi, the documentations always deals very explicitly with the issues of using one instance of an object with more than one thread.

However what do I need to know when there are some threads that have their own instance at the same time? Which interference could occur? How do I handle members like SimpleDateFormat that are quiet expensive to create?

Thanks Mike [;-)

+3  A: 

If each thread has it's own instance, and you don't use statics, then you are pretty safe :-)

No concurrencies issues !

KLE
+6  A: 

If code from each thread is accessing different instances (objects) of the same class, that is not a problem; unless, of course, those objects are accessing shared objects, such as class static objects.

As the documentation for SimpleDateFormat states:

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

One way of keeping separate instances for each thread would be to use a ThreadLocal object to keep track of separate instances.

Avi
+1  A: 

With respect to SimpleDateFormat, which as you point out is not threadsafe, you can instead opt to use the commons class FastDateFormat which is threadsafe and can be shared.

In more general terms, if you are sharing objects amongst threads always ensure that they are marked as threadsafe - the docs should always indicate this. If they are not threadsafe you will need to either limit concurrent access to them (e.g. via locks/synchronisation) or use multiple instances (one per thread). Generally, if you don't, you risk corrupting shared data/state with indeterminate consequences.

Joel
A: 

It seems "most people" use a thread-local date format. Something like:

private static final ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
     @Override public DateFormat initialValue() {
         return new SimpleDateFormat("fm/ts/tr", Locale.US);
     }
};
Tom Hawtin - tackline