使用简单日期格式不是线程安全的。为了避免这种情况,使用了ThreadLocal。它用于维护每个线程中的状态。 我们在使用它时应该小心,因为它可能会导致内存泄漏。 SDF 设置在线程局部上,稍后用于从中读取。 为了防止内存泄漏,也应该将其删除。 您能否用一个示例来说明同样的情况,其中在使用 SDF 后需要删除本地线程。
下面是代码
public class ConcurrentDateFormatAccess {
private ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat> () {
@Override
public DateFormat get() {
return super.get();
}
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy MM dd");
}
@Override
public void remove() {
super.remove();
}
@Override
public void set(DateFormat value) {
super.set(value);
}
};
public Date convertStringToDate(String dateString) throws ParseException {
return df.get().parse(dateString);
}
}
请帮助处理调用此函数并处理 threadLocal 的删除部分的客户端代码
最佳答案
package com.so;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ConcurrentDateFormatAccess {
private static ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat> () {
@Override
public DateFormat get() {
return super.get();
}
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy MM dd");
}
@Override
public void remove() {
super.remove();
}
@Override
public void set(DateFormat value) {
super.set(value);
}
};
public static Date convertStringToDate(String dateString) throws ParseException {
return df.get().parse(dateString);
}
public static void clean() throws ParseException {
df.remove();
}
}
您的客户:
package com.so;
import java.text.ParseException;
public class SOQ {
public static void main(String[] args) {
Thread thread1 = new Thread() {
@Override
public void run() {
try {
System.out.println(ConcurrentDateFormatAccess.convertStringToDate("2015 05 01"));
ConcurrentDateFormatAccess.clean();
} catch (ParseException e) {// TODO Auto-generated catch block
e.printStackTrace();
}
super.run();
}
};
Thread thread2 = new Thread() {
@Override
public void run() {
try {
System.out.println(ConcurrentDateFormatAccess.convertStringToDate("2015 05 02"));
ConcurrentDateFormatAccess.clean();
} catch (ParseException e) {
e.printStackTrace();
}
super.run();
}
};
thread1.start();
thread2.start();
}
}
关于java - 将 Thread local 与 SDF 结合使用并在使用后将其删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29947780/