001 package 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
022 import java.lang.ref.SoftReference;
023 import java.text.DateFormat;
024 import java.text.FieldPosition;
025 import java.text.ParsePosition;
026 import java.text.SimpleDateFormat;
027 import 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 */
037 public class ThreadSafeDateFormat
038 extends DateFormat
039 {
040 private static final long serialVersionUID = 3786090697869963812L;
041
042 private final String m_sDateFormat;
043
044 public ThreadSafeDateFormat( String sDateFormat )
045 {
046 m_sDateFormat = sDateFormat;
047 }
048
049 private final ThreadLocal<SoftReference<SimpleDateFormat>> m_formatCache = new ThreadLocal<SoftReference<SimpleDateFormat>>()
050 {
051 public SoftReference<SimpleDateFormat> get()
052 {
053 SoftReference<SimpleDateFormat> softRef = super.get();
054 if ( softRef == null || softRef.get() == null )
055 {
056 softRef = new SoftReference<SimpleDateFormat>( new SimpleDateFormat( m_sDateFormat ) );
057 super.set( softRef );
058 }
059 return softRef;
060 }
061 };
062
063 private DateFormat getDateFormat()
064 {
065 return m_formatCache.get().get();
066 }
067
068 public StringBuffer format( Date date, StringBuffer toAppendTo, FieldPosition fieldPosition )
069 {
070 return getDateFormat().format( date, toAppendTo, fieldPosition );
071 }
072
073 public Date parse( String source, ParsePosition pos )
074 {
075 return getDateFormat().parse( source, pos );
076 }
077 }