View Javadoc
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  
18  package org.apache.logging.log4j.core.util;
19  
20  import java.util.Objects;
21  
22  /**
23   * Creates the appropriate {@link NanoClock} instance for the current configuration.
24   */
25  public class NanoClockFactory {
26  
27      /**
28       * Enum over the different kinds of nano clocks this factory can create.
29       */
30      public static enum Mode {
31          /**
32           * Creates dummy nano clocks that always return a fixed value.
33           */
34          Dummy {
35              @Override
36              public NanoClock createNanoClock() {
37                  return new DummyNanoClock();
38              }
39          },
40          /**
41           * Creates real nano clocks which call {{System.nanoTime()}}.
42           */
43          System  {
44              @Override
45              public NanoClock createNanoClock() {
46                  return new SystemNanoClock();
47              }
48          },
49          ;
50          
51          public abstract NanoClock createNanoClock();
52      }
53      
54      private static volatile Mode mode = Mode.Dummy;
55      
56      /**
57       * Returns a new {@code NanoClock} determined by the mode of this factory.
58       * 
59       * @return the appropriate {@code NanoClock} for the factory mode
60       */
61      public static NanoClock createNanoClock() {
62          return mode.createNanoClock();
63      }
64      
65      /**
66       * Returns the factory mode.
67       * 
68       * @return the factory mode that determines which kind of nano clocks this factory creates
69       */
70      public static Mode getMode() {
71          return mode;
72      }
73      
74      /**
75       * Sets the factory mode.
76       * 
77       * @param mode the factory mode that determines which kind of nano clocks this factory creates
78       */
79      public static void setMode(Mode mode) {
80          NanoClockFactory.mode = Objects.requireNonNull(mode, "mode must be non-null");
81      }
82  }