View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, 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ücü
24   * @since 0.9.29
25   */
26  public class CachingDateFormatter {
27  
28  
29    long lastTimestamp = -1;
30    String cachedStr = null;
31    final SimpleDateFormat sdf;
32  
33    public CachingDateFormatter(String pattern) {
34      sdf = new SimpleDateFormat(pattern);
35    }
36  
37    public final String format(long now) {
38  
39      // SimpleDateFormat is not thread safe.
40  
41      // See also the discussion in http://jira.qos.ch/browse/LBCLASSIC-36
42      // DateFormattingThreadedThroughputCalculator and SelectiveDateFormattingRunnable
43      // are also note worthy
44  
45      // The now == lastTimestamp guard minimizes synchronization
46      synchronized (this) {
47        if (now != lastTimestamp) {
48          lastTimestamp = now;
49          cachedStr = sdf.format(new Date(now));
50        }
51        return cachedStr;
52      }
53    }
54  
55    public void setTimeZone(TimeZone tz) {
56      sdf.setTimeZone(tz);
57    }
58  }