搜索
您的当前位置:首页Threadlocal做SimpleDateFormat

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));
	}

}

因篇幅问题不能全部显示,请点此查看更多更全内容

Top