并发编程-SimpleDateFormat线程不安全及解决办法
2017-08-05 00:00
344 查看
一. 为什么SimpleDateFormat不是线程安全的?
Java源码如下:
一. 为什么SimpleDateFormat不是线程安全的?
Java源码如下:
/**
* 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.
*/
public class SimpleDateFormat extends DateFormat {
public Date parse(String text, ParsePosition pos){
calendar.clear(); // Clears all the time fields
// other logic ...
Date parsedDate = calendar.getTime();
}
}
abstract class DateFormat{
// other logic ...
protected Calendar calendar;
public Date parse(String source) throws ParseException{
ParsePosition pos = new ParsePosition(0);
Date result = parse(source, pos);
if (pos.index == 0)
throw new ParseException("Unparseable date: \"" + source + "\"" ,
pos.errorIndex);
return result;
}
}
如果我们把SimpleDateFormat定义成static成员变量,那么多个thread之间会共享这个sdf对象, 所以Calendar对象也会共享。
假定线程A和线程B都进入了parse(text, pos) 方法, 线程B执行到calendar.clear()后,线程A执行到calendar.getTime(), 那么就会有问题。
二. 问题重现:
public class SdfThreadTest2{
public static void main(String[] args) throws InterruptedException {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final String[] date = new String[]{"2017-01-01","2017-02-02","2017-03-03","2017-04-04","2017-05-05",
"2017-06-06","2017-07-07","2017-08-08","2017-09-09","2017-10-10","2017-11-11","2017-12-12"};
final ExecutorService es2 = Executors.newFixedThreadPool(12);
for(int i=0;i<12;i++){
final int j = i;
es2.execute(new Runnable(){
@Override
public void run() {
try {
System.out.println(j+ "->" + sdf.parse((date[j])));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}
三. 解决方案:
1. 解决方案a:
将SimpleDateFormat定义成局部变量:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
String str1 = "01-Jan-2010";
String str2 = sdf.format(sdf.parse(str1));
缺点:每调用一次方法就会创建一个SimpleDateFormat对象,方法结束又要作为垃圾回收。
2. 解决方案b:
加一把线程同步锁:synchronized(lock)
public class SdfThreadTest2{
public static void main(String[] args) throws InterruptedException {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final String[] date = new String[]{"2017-01-01","2017-02-02","2017-03-03","2017-04-04","2017-05-05",
"2017-06-06","2017-07-07","2017-08-08","2017-09-09","2017-10-10","2017-11-11","2017-12-12"};
final ExecutorService es2 = Executors.newFixedThreadPool(12);
for(int i=0;i<12;i++){
final int j = i;
es2.execute(new Runnable(){
@Override
public void run() {
try {
synchronized(sdf){
System.out.println(j+ "->" + sdf.parse((date[j])));
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}
缺点:性能较差,每次都要等待锁释放后其他线程才能进入
3. 解决方案c: (推荐)
使用ThreadLocal: 每个线程都将拥有自己的SimpleDateFormat对象副本。
写一个工具类:
public class DateUtil {
private static ThreadLocal<SimpleDateFormat> local = new ThreadLocal<SimpleDateFormat>();
public static Date parse(String str) throws Exception {
SimpleDateFormat sdf = local.get();
if (sdf == null) {
sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
local.set(sdf);
}
return sdf.parse(str);
}
public static String format(Date date) throws Exception {
SimpleDateFormat sdf = local.get();
if (sdf == null) {
sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
local.set(sdf);
}
return sdf.format(date);
}
}
Java源码如下:
一. 为什么SimpleDateFormat不是线程安全的?
Java源码如下:
/**
* 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.
*/
public class SimpleDateFormat extends DateFormat {
public Date parse(String text, ParsePosition pos){
calendar.clear(); // Clears all the time fields
// other logic ...
Date parsedDate = calendar.getTime();
}
}
abstract class DateFormat{
// other logic ...
protected Calendar calendar;
public Date parse(String source) throws ParseException{
ParsePosition pos = new ParsePosition(0);
Date result = parse(source, pos);
if (pos.index == 0)
throw new ParseException("Unparseable date: \"" + source + "\"" ,
pos.errorIndex);
return result;
}
}
如果我们把SimpleDateFormat定义成static成员变量,那么多个thread之间会共享这个sdf对象, 所以Calendar对象也会共享。
假定线程A和线程B都进入了parse(text, pos) 方法, 线程B执行到calendar.clear()后,线程A执行到calendar.getTime(), 那么就会有问题。
二. 问题重现:
public class SdfThreadTest2{
public static void main(String[] args) throws InterruptedException {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final String[] date = new String[]{"2017-01-01","2017-02-02","2017-03-03","2017-04-04","2017-05-05",
"2017-06-06","2017-07-07","2017-08-08","2017-09-09","2017-10-10","2017-11-11","2017-12-12"};
final ExecutorService es2 = Executors.newFixedThreadPool(12);
for(int i=0;i<12;i++){
final int j = i;
es2.execute(new Runnable(){
@Override
public void run() {
try {
System.out.println(j+ "->" + sdf.parse((date[j])));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}
三. 解决方案:
1. 解决方案a:
将SimpleDateFormat定义成局部变量:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
String str1 = "01-Jan-2010";
String str2 = sdf.format(sdf.parse(str1));
缺点:每调用一次方法就会创建一个SimpleDateFormat对象,方法结束又要作为垃圾回收。
2. 解决方案b:
加一把线程同步锁:synchronized(lock)
public class SdfThreadTest2{
public static void main(String[] args) throws InterruptedException {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final String[] date = new String[]{"2017-01-01","2017-02-02","2017-03-03","2017-04-04","2017-05-05",
"2017-06-06","2017-07-07","2017-08-08","2017-09-09","2017-10-10","2017-11-11","2017-12-12"};
final ExecutorService es2 = Executors.newFixedThreadPool(12);
for(int i=0;i<12;i++){
final int j = i;
es2.execute(new Runnable(){
@Override
public void run() {
try {
synchronized(sdf){
System.out.println(j+ "->" + sdf.parse((date[j])));
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}
缺点:性能较差,每次都要等待锁释放后其他线程才能进入
3. 解决方案c: (推荐)
使用ThreadLocal: 每个线程都将拥有自己的SimpleDateFormat对象副本。
写一个工具类:
public class DateUtil {
private static ThreadLocal<SimpleDateFormat> local = new ThreadLocal<SimpleDateFormat>();
public static Date parse(String str) throws Exception {
SimpleDateFormat sdf = local.get();
if (sdf == null) {
sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
local.set(sdf);
}
return sdf.parse(str);
}
public static String format(Date date) throws Exception {
SimpleDateFormat sdf = local.get();
if (sdf == null) {
sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
local.set(sdf);
}
return sdf.format(date);
}
}
相关文章推荐
- SimpleDateFormat线程不安全及解决办法
- SimpleDateFormat线程不安全及解决办法
- SimpleDateFormat线程不安全及解决办法
- Java SimpleDateFormat 线程不安全问题及解决方法
- SimpleDateFormat 的线程安全问题与解决方式
- 一个简单的Java对象池实现——可用来解决SimpleDateFormat的线程安全问题
- 解决SimpleDateFormat的线程不安全问题的方法:ThreadLocal
- SimpleDateFormat线程不安全及解决的方法
- SimpleDateFormat线程不安全示例及其解决方法
- SimpleDateFormat线程不安全及解决方式
- simpledateformat线程不安全解决方案
- SimpleDateFormat是线程不安全的,怎样使用使其安全?
- SimpleDateFormat 的线程安全问题与解决方案
- SimpleDateFormat的线程安全问题
- SimpleDateFormat的线程安全问题与解决方案(ThreadLocal)
- SimpleDateFormat 的线程安全问题与解决方案
- SimpleDateFormat 的线程安全问题与 ThreadLocal
- SimpleDateFormat的线程安全问题
- SimpleDateFormat线程不安全
- 关于jdk1.7的SimpleDateFormat类线程不安全