001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.issue.lbclassic36;
015
016import java.text.SimpleDateFormat;
017//import org.joda.time.format.DateTimeFormat;
018//import org.joda.time.format.DateTimeFormatter;
019
020import ch.qos.logback.core.contention.RunnableWithCounterAndDone;
021
022/**
023 * A runnable which behaves differently depending on the desired locking model.
024 * 
025 * @author Ralph Goers
026 * @author Ceki Gulcu
027 */
028public class SelectiveDateFormattingRunnable extends RunnableWithCounterAndDone {
029
030    public static final String ISO8601_PATTERN = "yyyy-MM-dd HH:mm:ss,SSS";
031
032    enum FormattingModel {
033        SDF, JODA;
034    }
035
036    FormattingModel model;
037    static long CACHE = 0;
038
039    static SimpleDateFormat SDF = new SimpleDateFormat(ISO8601_PATTERN);
040
041    // static final DateTimeFormatter JODA = DateTimeFormat
042    // .forPattern(ISO8601_PATTERN);
043
044    SelectiveDateFormattingRunnable(FormattingModel model) {
045        this.model = model;
046    }
047
048    public void run() {
049        switch (model) {
050        case SDF:
051            sdfRun();
052            break;
053        case JODA:
054            jodaRun();
055            break;
056        }
057    }
058
059    void sdfRun() {
060
061        for (;;) {
062            synchronized (SDF) {
063                long now = System.currentTimeMillis();
064                if (CACHE != now) {
065                    CACHE = now;
066                    SDF.format(now);
067                }
068            }
069            counter++;
070            if (done) {
071                return;
072            }
073        }
074    }
075
076    void jodaRun() {
077        for (;;) {
078            long now = System.currentTimeMillis();
079            if (isCacheStale(now)) {
080                // JODA.print(now);
081            }
082            counter++;
083            if (done) {
084                return;
085            }
086        }
087    }
088
089    private static boolean isCacheStale(long now) {
090        // synchronized (JODA) {
091        // if (CACHE != now) {
092        // CACHE = now;
093        // return true;
094        // }
095        // }
096        return false;
097    }
098
099}