1 package org.apache.maven.scm.util;
2
3 /*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22 import java.lang.ref.SoftReference;
23 import java.text.DateFormat;
24 import java.text.FieldPosition;
25 import java.text.ParsePosition;
26 import java.text.SimpleDateFormat;
27 import java.util.Date;
28
29 /**
30 * Thread-safe version of java.text.DateFormat.
31 * You can declare it as a static final variable:
32 * @author Olivier Lamy
33 * <code>
34 * private static final ThreadSafeDateFormat DATE_FORMAT = new ThreadSafeDateFormat( DATE_PATTERN );
35 * </code>
36 */
37 public class ThreadSafeDateFormat
38 extends DateFormat
39 {
40 private static final long serialVersionUID = 3786090697869963812L;
41
42 private final String dateFormat;
43
44 public ThreadSafeDateFormat( String sDateFormat )
45 {
46 dateFormat = sDateFormat;
47 }
48
49 private final ThreadLocal<SoftReference<SimpleDateFormat>> formatCache =
50 new ThreadLocal<SoftReference<SimpleDateFormat>>()
51 {
52 public SoftReference<SimpleDateFormat> get()
53 {
54 SoftReference<SimpleDateFormat> softRef = super.get();
55 if ( softRef == null || softRef.get() == null )
56 {
57 softRef = new SoftReference<SimpleDateFormat>( new SimpleDateFormat( dateFormat ) );
58 super.set( softRef );
59 }
60 return softRef;
61 }
62 };
63
64 private DateFormat getDateFormat()
65 {
66 return formatCache.get().get();
67 }
68
69 public StringBuffer format( Date date, StringBuffer toAppendTo, FieldPosition fieldPosition )
70 {
71 return getDateFormat().format( date, toAppendTo, fieldPosition );
72 }
73
74 public Date parse( String source, ParsePosition pos )
75 {
76 return getDateFormat().parse( source, pos );
77 }
78 }