For example:
static private DateFormat df = new SimpleDateFormat();
public static void format(final Date date) {
for (int i = 0; i < 10; i++)
new Thread(new Runnable() {
public void run() {
System.out.println(df.format(date));
}
});
}
The DateFormat
class is documented as not a synchronized class, but if we use just the format method, it can't change the status of the whole class?
Suppose it's declared private, how can one be sure that the code is thread safe?
What is the best way to fix this code?:
Using a different instance for every thread.
Using a synchronized block.