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