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 *
032 * @author Olivier Lamy
033 * <code>
034 * private static final ThreadSafeDateFormat DATE_FORMAT = new ThreadSafeDateFormat( DATE_PATTERN );
035 * </code>
036 */
037public class ThreadSafeDateFormat extends DateFormat {
038    private static final long serialVersionUID = 3786090697869963812L;
039
040    private final String dateFormat;
041
042    public ThreadSafeDateFormat(String sDateFormat) {
043        dateFormat = sDateFormat;
044    }
045
046    private final ThreadLocal<SoftReference<SimpleDateFormat>> formatCache =
047            new ThreadLocal<SoftReference<SimpleDateFormat>>() {
048                public SoftReference<SimpleDateFormat> get() {
049                    SoftReference<SimpleDateFormat> softRef = super.get();
050                    if (softRef == null || softRef.get() == null) {
051                        softRef = new SoftReference<>(new SimpleDateFormat(dateFormat));
052                        super.set(softRef);
053                    }
054                    return softRef;
055                }
056            };
057
058    private DateFormat getDateFormat() {
059        return formatCache.get().get();
060    }
061
062    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
063        return getDateFormat().format(date, toAppendTo, fieldPosition);
064    }
065
066    public Date parse(String source, ParsePosition pos) {
067        return getDateFormat().parse(source, pos);
068    }
069}