1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.tomcat.util.http;
18
19 import java.text.ParseException;
20 import java.text.SimpleDateFormat;
21 import java.util.Date;
22 import java.util.Locale;
23 import java.util.Queue;
24 import java.util.TimeZone;
25 import java.util.concurrent.ConcurrentLinkedQueue;
26
27 /**
28  * A thread safe wrapper around {@link SimpleDateFormat} that does not make use
29  * of ThreadLocal and - broadly - only creates enough SimpleDateFormat objects
30  * to satisfy the concurrency requirements.
31  */

32 public class ConcurrentDateFormat {
33
34     private final String format;
35     private final Locale locale;
36     private final TimeZone timezone;
37     private final Queue<SimpleDateFormat> queue = new ConcurrentLinkedQueue<>();
38
39     public ConcurrentDateFormat(String format, Locale locale, TimeZone timezone) {
40         this.format = format;
41         this.locale = locale;
42         this.timezone = timezone;
43         SimpleDateFormat initial = createInstance();
44         queue.add(initial);
45     }
46
47     public String format(Date date) {
48         SimpleDateFormat sdf = queue.poll();
49         if (sdf == null) {
50             sdf = createInstance();
51         }
52         String result = sdf.format(date);
53         queue.add(sdf);
54         return result;
55     }
56
57     public Date parse(String source) throws ParseException {
58         SimpleDateFormat sdf = queue.poll();
59         if (sdf == null) {
60             sdf = createInstance();
61         }
62         Date result = sdf.parse(source);
63         queue.add(sdf);
64         return result;
65     }
66
67     private SimpleDateFormat createInstance() {
68         SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
69         sdf.setTimeZone(timezone);
70         return sdf;
71     }
72 }
73