001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017
018package org.apache.logging.log4j.core.util;
019
020import java.util.Objects;
021
022/**
023 * Creates the appropriate {@link NanoClock} instance for the current configuration.
024 */
025public class NanoClockFactory {
026
027    /**
028     * Enum over the different kinds of nano clocks this factory can create.
029     */
030    public static enum Mode {
031        /**
032         * Creates dummy nano clocks that always return a fixed value.
033         */
034        Dummy {
035            @Override
036            public NanoClock createNanoClock() {
037                return new DummyNanoClock();
038            }
039        },
040        /**
041         * Creates real nano clocks which call {{System.nanoTime()}}.
042         */
043        System  {
044            @Override
045            public NanoClock createNanoClock() {
046                return new SystemNanoClock();
047            }
048        },
049        ;
050        
051        public abstract NanoClock createNanoClock();
052    }
053    
054    private static volatile Mode mode = Mode.Dummy;
055    
056    /**
057     * Returns a new {@code NanoClock} determined by the mode of this factory.
058     * 
059     * @return the appropriate {@code NanoClock} for the factory mode
060     */
061    public static NanoClock createNanoClock() {
062        return mode.createNanoClock();
063    }
064    
065    /**
066     * Returns the factory mode.
067     * 
068     * @return the factory mode that determines which kind of nano clocks this factory creates
069     */
070    public static Mode getMode() {
071        return mode;
072    }
073    
074    /**
075     * Sets the factory mode.
076     * 
077     * @param mode the factory mode that determines which kind of nano clocks this factory creates
078     */
079    public static void setMode(Mode mode) {
080        NanoClockFactory.mode = Objects.requireNonNull(mode, "mode must be non-null");
081    }
082}