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.hash; 16 17 import com.google.common.base.Supplier; 18 import java.util.concurrent.atomic.AtomicLong; 19 20 /** 21 * Source of {@link LongAddable} objects that deals with GWT, Unsafe, and all that. 22 * 23 * @author Louis Wasserman 24 */ 25 final class LongAddables { 26 private static final Supplier<LongAddable> SUPPLIER; 27 28 static { 29 Supplier<LongAddable> supplier; 30 try { LongAdder()31 new LongAdder(); // trigger static initialization of the LongAdder class, which may fail 32 supplier = 33 new Supplier<LongAddable>() { 34 @Override 35 public LongAddable get() { 36 return new LongAdder(); 37 } 38 }; 39 } catch (Throwable t) { // we really want to catch *everything* 40 supplier = 41 new Supplier<LongAddable>() { 42 @Override 43 public LongAddable get() { 44 return new PureJavaLongAddable(); 45 } 46 }; 47 } 48 SUPPLIER = supplier; 49 } 50 create()51 public static LongAddable create() { 52 return SUPPLIER.get(); 53 } 54 55 private static final class PureJavaLongAddable extends AtomicLong implements LongAddable { 56 @Override increment()57 public void increment() { 58 getAndIncrement(); 59 } 60 61 @Override add(long x)62 public void add(long x) { 63 getAndAdd(x); 64 } 65 66 @Override sum()67 public long sum() { 68 return get(); 69 } 70 } 71 } 72