如何知道java SE类或方法是否是线程安全的? [英] how to know if java SE class or method is thread safe?
问题描述
例如:
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));
}
});
}
DateFormat类记录为未同步的Class,但如果我们只使用格式方法,它不能改变孔类的法定?
DateFormat class it documented as not synchornized Class, but if we use just the format Method, it can't change the statut of the hole Class?
假设它被声明为私有,如何确保此代码是线程安全的?
Suppose it's declared private, how to be sure 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.
推荐答案
- 对于标准Java SE类,了解类是否是线程安全的最佳方法是仔细阅读其文档。始终阅读课程文档和方法文档。如果要么说它不同步或不是线程安全的,你知道它不是线程安全的。
-
因此,
DateFormat
class 不线程安全。文档具体说:- For a standard Java SE class, the best way to know whether or not the class is thread-safe is to carefully read its documentation. Always read both the class documentation and the method documentation. If either say it's not synchronized or not thread-safe, you know it's not thread-safe.
Therefore, the
DateFormat
class is not thread safe. The documentation specifically says:
日期格式不同步。建议为每个线程创建单独的格式实例。如果多个线程同时访问某个格式,则必须在外部同步。
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.
-
声明字段
private
不使您的实现线程安全。private
仅表示外部类无法看到该字段。让我们来看看你的方法: Declaring a field
private
does not make your implementation thread-safe.private
merely says that outside classes can't see that field. Let's look at your method:for (int i=0;i<10;i++) new Thread(new Runnable(){ public void run(){ System.out.println(df.format(date)); } });
您创建的
Runnable
对象是匿名的类。匿名类是内部类,可以访问其周围类的私有字段。如果不是这样,你的程序将无法编译 - 他们无法访问df
字段。The
Runnable
objects that you create are anonymous classes. Anonymous classes are inner classes, which have access to private fields of their surrounding class. If it wasn't so, your program would not compile - they could not access thedf
field.但是他们能。所以实际上你有10个线程都访问你的
DateFormat
对象,由df
引用。由于我们已经知道DateFormat
而不是线程安全,因此您的程序不是线程安全的。But they can. So in fact you are having 10 threads that are all accessing your one
DateFormat
object, referred to bydf
. Since we already know thatDateFormat
is not thread-safe, your program is not thread-safe.这篇关于如何知道java SE类或方法是否是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!