• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 
15 package com.google.common.cache;
16 
17 import com.google.common.annotations.GwtCompatible;
18 import com.google.common.base.Supplier;
19 import java.util.concurrent.atomic.AtomicLong;
20 
21 /**
22  * Source of {@link LongAddable} objects that deals with GWT, Unsafe, and all that.
23  *
24  * @author Louis Wasserman
25  */
26 @GwtCompatible(emulated = true)
27 @ElementTypesAreNonnullByDefault
28 final class LongAddables {
29   private static final Supplier<LongAddable> SUPPLIER;
30 
31   static {
32     Supplier<LongAddable> supplier;
33     try {
34       // trigger static initialization of the LongAdder class, which may fail
35       LongAdder unused = new LongAdder();
36       supplier =
37           new Supplier<LongAddable>() {
38             @Override
39             public LongAddable get() {
40               return new LongAdder();
41             }
42           };
43     } catch (Throwable t) { // we really want to catch *everything*
44       supplier =
45           new Supplier<LongAddable>() {
46             @Override
47             public LongAddable get() {
48               return new PureJavaLongAddable();
49             }
50           };
51     }
52     SUPPLIER = supplier;
53   }
54 
create()55   public static LongAddable create() {
56     return SUPPLIER.get();
57   }
58 
59   private static final class PureJavaLongAddable extends AtomicLong implements LongAddable {
60     @Override
increment()61     public void increment() {
62       getAndIncrement();
63     }
64 
65     @Override
add(long x)66     public void add(long x) {
67       getAndAdd(x);
68     }
69 
70     @Override
sum()71     public long sum() {
72       return get();
73     }
74   }
75 }
76