Tomcat8中的并发ConcurrentDateFormat的实现
生活随笔
收集整理的這篇文章主要介紹了
Tomcat8中的并发ConcurrentDateFormat的实现
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
今天偶然想起翻翻tomcat源碼,果然每次翻源碼都有不小的收獲。
下面我?guī)ьI(lǐng)大家看下tomcat8中的ConcurrentDateFormat源碼和實(shí)現(xiàn)。
源碼如下:
/*** {@link SimpleDateFormat}的線程安全包裝器。* 不使用ThreadLocal,創(chuàng)建足夠的SimpleDateFormat對象來滿足并發(fā)性要求。*/ public class ConcurrentDateFormat {private final String format;private final Locale locale;private final TimeZone timezone;private final Queue<SimpleDateFormat> queue = new ConcurrentLinkedQueue<>();public static final String RFC1123_DATE = "EEE, dd MMM yyyy HH:mm:ss zzz";public static final TimeZone GMT = TimeZone.getTimeZone("GMT");private static final ConcurrentDateFormat FORMAT_RFC1123;static {FORMAT_RFC1123 = new ConcurrentDateFormat(RFC1123_DATE, Locale.US, GMT);}public static String formatRfc1123(Date date) {return FORMAT_RFC1123.format(date);}public ConcurrentDateFormat(String format, Locale locale,TimeZone timezone) {this.format = format;this.locale = locale;this.timezone = timezone;SimpleDateFormat initial = createInstance();queue.add(initial);}public String format(Date date) {SimpleDateFormat sdf = queue.poll();if (sdf == null) {sdf = createInstance();}String result = sdf.format(date);queue.add(sdf);return result;}private SimpleDateFormat createInstance() {SimpleDateFormat sdf = new SimpleDateFormat(format, locale);sdf.setTimeZone(timezone);return sdf;} }tomcat8中并沒有采用ThreadLocal的實(shí)現(xiàn)方式,而是用了一個(gè)并發(fā)隊(duì)列。
format時(shí)先從隊(duì)列中彈出一個(gè)SimpleDateFormat,為null時(shí)則創(chuàng)建并添加進(jìn)隊(duì)列。
這樣隨著線程數(shù)的增長,隊(duì)列中的SimpleDateFormat對象將會趨于飽和,減少高并發(fā)下對象的創(chuàng)建,提高性能。
轉(zhuǎn)載于:https://my.oschina.net/qq596392912/blog/877849
總結(jié)
以上是生活随笔為你收集整理的Tomcat8中的并发ConcurrentDateFormat的实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql两主多从
- 下一篇: A/B测试:概念 ≠ 执行