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 final 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 public abstract NanoClock createNanoClock();
51 }
52
53 private static volatile Mode mode = Mode.Dummy;
54
55 private NanoClockFactory() {
56 }
57
58 /**
59 * Returns a new {@code NanoClock} determined by the mode of this factory.
60 *
61 * @return the appropriate {@code NanoClock} for the factory mode
62 */
63 public static NanoClock createNanoClock() {
64 return mode.createNanoClock();
65 }
66
67 /**
68 * Returns the factory mode.
69 *
70 * @return the factory mode that determines which kind of nano clocks this factory creates
71 */
72 public static Mode getMode() {
73 return mode;
74 }
75
76 /**
77 * Sets the factory mode.
78 *
79 * @param mode the factory mode that determines which kind of nano clocks this factory creates
80 */
81 public static void setMode(Mode mode) {
82 NanoClockFactory.mode = Objects.requireNonNull(mode, "mode must be non-null");
83 }
84 }