001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.maven.scm.util; 020 021import java.lang.ref.SoftReference; 022import java.text.DateFormat; 023import java.text.FieldPosition; 024import java.text.ParsePosition; 025import java.text.SimpleDateFormat; 026import java.util.Date; 027 028/** 029 * Thread-safe version of java.text.DateFormat. 030 * You can declare it as a static final variable: 031 * @author Olivier Lamy 032 * <code> 033 * private static final ThreadSafeDateFormat DATE_FORMAT = new ThreadSafeDateFormat( DATE_PATTERN ); 034 * </code> 035 */ 036public class ThreadSafeDateFormat extends DateFormat { 037 private static final long serialVersionUID = 3786090697869963812L; 038 039 private final String dateFormat; 040 041 public ThreadSafeDateFormat(String sDateFormat) { 042 dateFormat = sDateFormat; 043 } 044 045 private final ThreadLocal<SoftReference<SimpleDateFormat>> formatCache = 046 new ThreadLocal<SoftReference<SimpleDateFormat>>() { 047 public SoftReference<SimpleDateFormat> get() { 048 SoftReference<SimpleDateFormat> softRef = super.get(); 049 if (softRef == null || softRef.get() == null) { 050 softRef = new SoftReference<>(new SimpleDateFormat(dateFormat)); 051 super.set(softRef); 052 } 053 return softRef; 054 } 055 }; 056 057 private DateFormat getDateFormat() { 058 return formatCache.get().get(); 059 } 060 061 public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { 062 return getDateFormat().format(date, toAppendTo, fieldPosition); 063 } 064 065 public Date parse(String source, ParsePosition pos) { 066 return getDateFormat().parse(source, pos); 067 } 068}