java的SimpleDateFormat线程不安全出问题了,虚竹教你多种解决方案(1)

还有兄弟不知道网络安全面试可以提前刷题吗?费时一周整理的160+网络安全面试题,金九银十,做网络安全面试里的显眼包!

王岚嵚工程师面试题(附答案),只能帮兄弟们到这儿了!如果你能答对70%,找一个安全工作,问题不大。

对于有1-3年工作经验,想要跳槽的朋友来说,也是很好的温习资料!

【完整版领取方式在文末!!】

93道网络安全面试题

需要体系化学习资料的朋友,可以加我V获取:vip204888 (备注网络安全)

内容实在太多,不一一截图了

黑客学习资源推荐

最后给大家分享一份全套的网络安全学习资料,给那些想学习 网络安全的小伙伴们一点帮助!

对于从来没有接触过网络安全的同学,我们帮你准备了详细的学习成长路线图。可以说是最科学最系统的学习路线,大家跟着这个大的方向学习准没问题。

1️⃣零基础入门
① 学习路线

对于从来没有接触过网络安全的同学,我们帮你准备了详细的学习成长路线图。可以说是最科学最系统的学习路线,大家跟着这个大的方向学习准没问题。

image

② 路线对应学习视频

同时每个成长路线对应的板块都有配套的视频提供:

image-20231025112050764

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化资料的朋友,可以点击这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

由源码可知,最后是调用**parsedDate = calb.establish(calendar).getTime();**获取返回值。方法的参数是calendar,calendar可以被多个线程访问到,存在线程不安全问题。

我们再来看看**calb.establish(calendar)**的源码

image-20210805827464

calb.establish(calendar)方法先后调用了cal.clear()cal.set(),先清理值,再设值。但是这两个操作并不是原子性的,也没有线程安全机制来保证,导致多线程并发时,可能会引起cal的值出现问题了。

验证SimpleDateFormat线程不安全


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()+" 格式化失败 ");

}

}

}

}

image-20210805754416

出现了两次false,说明线程是不安全的。而且还抛异常,这个就严重了。

解决方案

========================================================================

解决方案1:不要定义为static变量,使用局部变量


就是要使用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()+" 格式化失败 ");

}

}

}

}

image-20210805936439

由图可知,已经保证了线程安全,但这种方案不建议在高并发场景下使用,因为会创建大量的SimpleDateFormat对象,影响性能。

解决方案2:加锁:synchronized锁和Lock锁


加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()+" 格式化失败 ");

}

}

}

}

image-2021080591591

如图所示,线程是安全的。定义了全局变量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();

}

}

}

}

image-20210805940496

由结果可知,加Lock锁也能保证线程安全。要注意的是,最后一定要释放锁,代码里在finally里增加了lock.unlock();,保证释放锁。

在高并发的情况下会影响性能。这种方案不建议在高并发场景下使用

解决方案3:使用ThreadLocal方式


使用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();

}

}

}

}

image-202108059729

使用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));

} catch (Exception e) {

e.printStackTrace();

System.out.println(Thread.currentThread().getName()+" 格式化失败 ");

}

}

}

}

image-2021080591443373

使用DateTimeFormatter能保证线程安全,且效率也是挺高的。适合高并发场景使用

解决方案5:使用FastDateFormat 替换SimpleDateFormat


使用FastDateFormat 替换SimpleDateFormat(FastDateFormat 是线程安全的,Apache Commons Lang包支持,不受限于java版本)

public class FastDateFormatDemo6 {

private static FastDateFormat fastDateFormat = FastDateFormat.getInstance(“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 = fastDateFormat.format(new Date());

Date parseDate = fastDateFormat.parse(dateString);

String dateString2 = fastDateFormat.format(parseDate);

System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));

} catch (Exception e) {

e.printStackTrace();

System.out.println(Thread.currentThread().getName()+" 格式化失败 ");

}

}

}

}

使用FastDateFormat能保证线程安全,且效率也是挺高的。适合高并发场景使用

FastDateFormat源码分析

Apache Commons Lang 3.5

//FastDateFormat@Overridepublic String format(final Date date) { return printer.format(date);} @Override public String format(final Date date) { final Calendar c = Calendar.getInstance(timeZone, locale); c.setTime(date); return applyRulesToString©; }

源码中 Calender 是在 format 方法里创建的,肯定不会出现 setTime 的线程安全问题。这样线程安全疑惑解决了。那还有性能问题要考虑?

我们来看下FastDateFormat是怎么获取的

FastDateFormat.getInstance();FastDateFormat.getInstance(CHINESE_DATE_TIME_PATTERN);

看下对应的源码

学习路线:

这个方向初期比较容易入门一些,掌握一些基本技术,拿起各种现成的工具就可以开黑了。不过,要想从脚本小子变成黑客大神,这个方向越往后,需要学习和掌握的东西就会越来越多以下是网络渗透需要学习的内容:
在这里插入图片描述

需要体系化学习资料的朋友,可以加我V获取:vip204888 (备注网络安全)

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化资料的朋友,可以点击这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 28
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值