您的位置:首页 > 其它

"Calendars" and "DateFormats" should not be static

2017-02-22 23:57 543 查看
参见:Call to method of static java.text.DateFormat not advisable?

级别:bug, multi-threading

Not all classes in the standard Java library were written to be thread-safe. Using them in a multi-threaded manner is highly likely to cause data problems or exceptions at runtime.
This rule raises an issue when an instance of Calendar, DateFormat, javax.xml.xpath.XPath, or javax.xml.validation.SchemaFactory is marked static.


Noncompliant Code Example:

public class MyClass {
static private SimpleDateFormat format = new SimpleDateFormat("HH-mm-ss");  // Noncompliant
static private Calendar calendar = Calendar.getInstance();  // Noncompliant


Compliant Solution:

public class MyClass {
private SimpleDateFormat format = new SimpleDateFormat("HH-mm-ss");
private Calendar calendar = Calendar.getInstance();


后面这种solution也不能保证安全性,要保证完全安全性只能是使用局部变量进行栈封闭
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐