• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 package org.chromium.base;
6 
7 import java.util.HashMap;
8 
9 import javax.annotation.concurrent.NotThreadSafe;
10 
11 /**
12  * Defines a feature flag for use in Java.
13  *
14  * Duplicate flag definitions are not permitted, so only a single
15  * instance can be created with a given feature name.
16  *
17  * To create a flag, instantiate a concrete subclass, i.e. CachedFlag, MutableFlagWithSafeDefault or
18  * PostNativeFlag.
19  *
20  * This class and its subclasses are not thread safe.
21  */
22 @NotThreadSafe
23 public abstract class Flag {
24     private static HashMap<String, Flag> sFlagsCreated = new HashMap<>();
25     protected final String mFeatureName;
26     protected Boolean mValue;
27 
Flag(String featureName)28     protected Flag(String featureName) {
29         assert !sFlagsCreated.containsKey(featureName)
30                 : "Duplicate flag creation for feature: " + featureName;
31         mFeatureName = featureName;
32         sFlagsCreated.put(mFeatureName, this);
33     }
34 
35     /**
36      * @return the unique name of the feature flag.
37      */
getFeatureName()38     public String getFeatureName() {
39         return mFeatureName;
40     }
41 
42     /**
43      * Checks if a feature flag is enabled.
44      * @return whether the feature should be considered enabled.
45      */
isEnabled()46     public abstract boolean isEnabled();
47 
clearInMemoryCachedValueForTesting()48     protected abstract void clearInMemoryCachedValueForTesting();
49 
50     /**
51      * Resets the list of active flag instances. This shouldn't be used directly by individual
52      * tests other than those that exercise Flag subclasses.
53      */
resetFlagsForTesting()54     public static void resetFlagsForTesting() {
55         resetAllInMemoryCachedValuesForTesting();
56         sFlagsCreated.clear();
57     }
58 
59     /**
60      * Resets the in-memory cache of every Flag instance. This shouldn't be used directly by
61      * individual tests other than those that exercise Flag subclasses.
62      */
resetAllInMemoryCachedValuesForTesting()63     public static void resetAllInMemoryCachedValuesForTesting() {
64         for (Flag flag : sFlagsCreated.values()) {
65             flag.clearInMemoryCachedValueForTesting();
66         }
67     }
68 }
69