How do I know if a Java se class or method is thread safe?
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 it records is not a synchronization class, but if we only use the format method, it cannot change the legal name of the hole class?
Assuming it is declared private, how do you ensure that this code is thread safe?
What is the best way to fix this code?:
1_ Using a different instance for every Thread. 2_ Using a synchronized block.
Solution
>For standard Java se classes, the best way to know if the class is thread safe is to read its documentation carefully Always read the course and method documentation If it's either out of sync or thread safe, you know it's not thread safe
>Declaring fields private does not make your implementation thread safe Private only said that the outside class could not see that field Let's take a look at your method:
for (int i=0;i<10;i++) new Thread(new Runnable(){ public void run(){ System.out.println(df.format(date)); } });
The runnable object you created is an anonymous class An anonymous class is an inner class that can access the private fields of its surrounding classes If not, your program won't compile - they won't be able to access the DF field
But they can So you actually have 10 threads accessing one of your dateformat objects, referenced by DF Since we already know that dateformat is not thread safe, your program is not thread safe. > In addition, if two external threads refer to your object (I mean the object containing DF. You didn't give the class declaration, so I don't know what its name is) They refer to instances of the same class If they both call format at the same time, both will run dateformat with the same private DF format. Therefore, this is not thread safe. > For thread safety, you need to synchronize or use other types of locks on the object (there is a lock for all possible threads accessing it), which is what the document says. > Another way is to have a completely local object visible to only one thread Not a field - a local variable that can access a uniquely created dateformat instance (so there is a new copy every time the method is called) But pay attention to anonymous courses! In your example, even if DF is a local field of the format method, it is still not thread safe because all threads will access the same copy