View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.util;
15  
16  import java.text.SimpleDateFormat;
17  import java.util.Date;
18  import java.util.TimeZone;
19  
20  /**
21   * A synchronized implementation of  SimpleDateFormat which uses caching internally.
22   *
23   * @author Ceki Gülcü
24   * @since 0.9.29
25   */
26  public class CachingDateFormatter {
27  
28      long lastTimestamp = -1;
29      String cachedStr = null;
30      final SimpleDateFormat sdf;
31  
32      public CachingDateFormatter(String pattern) {
33          sdf = new SimpleDateFormat(pattern);
34      }
35  
36      public final String format(long now) {
37  
38          // SimpleDateFormat is not thread safe.
39  
40          // See also the discussion in http://jira.qos.ch/browse/LBCLASSIC-36
41          // DateFormattingThreadedThroughputCalculator and SelectiveDateFormattingRunnable
42          // are also noteworthy
43  
44          // The now == lastTimestamp guard minimizes synchronization
45          synchronized (this) {
46              if (now != lastTimestamp) {
47                  lastTimestamp = now;
48                  cachedStr = sdf.format(new Date(now));
49              }
50              return cachedStr;
51          }
52      }
53  
54      public void setTimeZone(TimeZone tz) {
55          sdf.setTimeZone(tz);
56      }
57  }