我声明了以下变量:
private static Calendar calendar = Calendar.getInstance();
我在静态方法中使用该变量“日历”,如下所示:
myStaticMethod(String reqDate){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date some_date;
long seconds = 0;
int value = 10;
try {
some_date = df.parse(reqDate);
calendar.setTime(some_date);
calendar.add(Calendar.DATE, value);
Date effValueDate = calendar.getTime();
seconds = (effValueDate .getTime() - System.currentTimeMillis()) / 1000;
} catch (ParseException e) {
//---Do---something----
}
}
我收到以下 Sonar 错误:
Make "calendar" an instance variable.
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.
这是我的解决方案,但我不确定解决方案质量是否足够好。
myStaticMethod(String reqDate) {
Calendar calendar = Calendar.getInstance();
// the do the next processing
}
那么我该如何修复这个错误...在这种情况下我可以使用本地Calendar
变量而不是类变量,或者是否有任何其他智能方法来解决这个问题。
最佳答案
引起 Sonar 警告的原因是calendar
对象可以从多个线程更新。
或者,正如您所说,您可以将日历声明为方法的本地日历。
或者 1) 在代码中创建一个同步块(synchronized block)。 (使用本地日历
更好)
Date effValueDate ;
synchronized(calendar) {
calendar.setTime(some_date);
calendar.add(Calendar.DATE, value);
effValueDate = calendar.getTime();
}
- 建议:使用新的 Java API 类来获取日期和时间 (
java.time
)。
// or use DateTimeFormatter.ISO_LOCAL_DATE
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateTime date = LocalDate.parse(reqDate, pattern).plusDays(value).atStartOfDay();
Duration duration= Duration.between(date, LocalDateTime.now());
long seconds = duration.getSeconds();
Read more关于新 API
关于java - 静态日历变量上的 Sonar 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68197887/