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