网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
{
…
Date parsedDate;
try {
parsedDate = calb.establish(calendar).getTime();
// If the year value is ambiguous,
// then the two-digit year == the default start year
if (ambiguousYear[0]) {
if (parsedDate.before(defaultCenturyStart)) {
parsedDate = calb.addYear(100).establish(calendar).getTime();
}
}
}
// An IllegalArgumentException will be thrown by Calendar.getTime()
// if any fields are out of range, e.g., MONTH == 17.
catch (IllegalArgumentException e) {
pos.errorIndex = start;
pos.index = oldStart;
return null;
}
return parsedDate;
}
由源码可知,最后是调用**parsedDate = calb.establish(calendar).getTime();**获取返回值。方法的参数是calendar,calendar可以被多个线程访问到,存在线程不安全问题。
我们再来看看**calb.establish(calendar)**的源码
calb.establish(calendar)方法先后调用了cal.clear()和cal.set(),先清理值,再设值。但是这两个操作并不是原子性的,也没有线程安全机制来保证,导致多线程并发时,可能会引起cal的值出现问题了。
public class SimpleDateFormatDemoTest {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
public static void main(String[] args) {
//1、创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、为线程池分配任务
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、关闭线程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
String dateString = simpleDateFormat.format(new Date());
try {
Date parseDate = simpleDateFormat.parse(dateString);
String dateString2 = simpleDateFormat.format(parseDate);
System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失败 ");
}
}
}
}
出现了两次false,说明线程是不安全的。而且还抛异常,这个就严重了。
========================================================================
就是要使用SimpleDateFormat对象进行format或parse时,再定义为局部变量。就能保证线程安全。
public class SimpleDateFormatDemoTest1 {
public static void main(String[] args) {
//1、创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、为线程池分配任务
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、关闭线程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
String dateString = simpleDateFormat.format(new Date());
try {
Date parseDate = simpleDateFormat.parse(dateString);
String dateString2 = simpleDateFormat.format(parseDate);
System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失败 ");
}
}
}
}
由图可知,已经保证了线程安全,但这种方案不建议在高并发场景下使用,因为会创建大量的SimpleDateFormat对象,影响性能。
加synchronized锁
SimpleDateFormat对象还是定义为全局变量,然后需要调用SimpleDateFormat进行格式化时间时,再用synchronized保证线程安全。
public class SimpleDateFormatDemoTest2 {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
public static void main(String[] args) {
//1、创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、为线程池分配任务
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、关闭线程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
try {
synchronized (simpleDateFormat){
String dateString = simpleDateFormat.format(new Date());
Date parseDate = simpleDateFormat.parse(dateString);
String dateString2 = simpleDateFormat.format(parseDate);
System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));
}
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失败 ");
}
}
}
}
如图所示,线程是安全的。定义了全局变量SimpleDateFormat,减少了创建大量SimpleDateFormat对象的损耗。但是使用synchronized锁,
同一时刻只有一个线程能执行锁住的代码块,在高并发的情况下会影响性能。但这种方案不建议在高并发场景下使用
加Lock锁
加Lock锁和synchronized锁原理是一样的,都是使用锁机制保证线程的安全。
public class SimpleDateFormatDemoTest3 {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
private static Lock lock = new ReentrantLock();
public static void main(String[] args) {
//1、创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、为线程池分配任务
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、关闭线程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
try {
lock.lock();
String dateString = simpleDateFormat.format(new Date());
Date parseDate = simpleDateFormat.parse(dateString);
String dateString2 = simpleDateFormat.format(parseDate);
System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失败 ");
}finally {
lock.unlock();
}
}
}
}
由结果可知,加Lock锁也能保证线程安全。要注意的是,最后一定要释放锁,代码里在finally里增加了lock.unlock();,保证释放锁。
在高并发的情况下会影响性能。这种方案不建议在高并发场景下使用
使用ThreadLocal保证每一个线程有SimpleDateFormat对象副本。这样就能保证线程的安全。
public class SimpleDateFormatDemoTest4 {
private static ThreadLocal threadLocal = new ThreadLocal(){
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
}
};
public static void main(String[] args) {
//1、创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、为线程池分配任务
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、关闭线程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
try {
String dateString = threadLocal.get().format(new Date());
Date parseDate = threadLocal.get().parse(dateString);
String dateString2 = threadLocal.get().format(parseDate);
System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失败 ");
}finally {
//避免内存泄漏,使用完threadLocal后要调用remove方法清除数据
threadLocal.remove();
}
}
}
}
使用ThreadLocal能保证线程安全,且效率也是挺高的。适合高并发场景使用。
解决方案4:使用DateTimeFormatter代替SimpleDateFormat
使用DateTimeFormatter代替SimpleDateFormat(DateTimeFormatter是线程安全的,java 8+支持)
DateTimeFormatter介绍 传送门:万字博文教你搞懂java源码的日期和时间相关用法
public class DateTimeFormatterDemoTest5 {
private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss”);
public static void main(String[] args) {
//1、创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、为线程池分配任务
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、关闭线程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
try {
String dateString = dateTimeFormatter.format(LocalDateTime.now());
TemporalAccessor temporalAccessor = dateTimeFormatter.parse(dateString);
String dateString2 = dateTimeFormatter.format(temporalAccessor);
System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));
一、网安学习成长路线图
网安所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
二、网安视频合集
观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
三、精品网安学习书籍
当我学到一定基础,有自己的理解能力的时候,会去阅读一些前辈整理的书籍或者手写的笔记资料,这些笔记详细记载了他们对一些技术点的理解,这些理解是比较独到,可以学到不一样的思路。
四、网络安全源码合集+工具包
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
五、网络安全面试题
最后就是大家最关心的网络安全面试题板块
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!