Threadlocal做SimpleDateFormat

1.Threadlocal

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of
thread-local instances are subject to garbage collection (unless other references to these copies exist).
每个线程都拥有对其本地线程副本的隐式引用 只要线程处于活动状态并且ThreadLocal是变量 实例可访问;一个线程消失后,它的所有副本 线程局部实例受垃圾回收(除非其他 存在对这些副本的引用)。

ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。

在这里插入图片描述

2.demo

package com.yinzhen.demo.thread;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ThreadLocalDateFormatDemo {
	
    public static final String yyyyMMddHHmmss = "yyyyMMddHHmmss";
    public static final String yyyyMMdd = "yyyy-MM-dd";
	
	private  static Map<String,ThreadLocal<SimpleDateFormat>> dfMap = new HashMap<>(); 
	private static final Object lockObj = new Object();
	
	private static SimpleDateFormat getDfByPattern(String pattern) {
		ThreadLocal<SimpleDateFormat> df = dfMap.get(pattern);
		if(df==null) {
			synchronized(lockObj) {
				df = dfMap.get(pattern);
				if(df ==null) {
					df = new ThreadLocal<SimpleDateFormat>() {

						@Override
						protected SimpleDateFormat initialValue() {
							
							return new SimpleDateFormat(pattern);
						}
						
					};
					dfMap.put(pattern, df);
				}
			}
		}
		return df.get();
	}
	
	/**
	 * 本类中提供了部分格式,如果要使用自己的格式请保证格式正确,否则会返回null
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String format(Date date,String pattern) {
		try {
			return getDfByPattern(pattern).format(date);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static void main(String[] args) {
		System.out.println(ThreadLocalDateFormatDemo.format(new Date(), "abcd"));
		System.out.println(ThreadLocalDateFormatDemo.format(new Date(), "yyyy"));
		System.out.println(ThreadLocalDateFormatDemo.format(new Date(), yyyyMMdd));
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值