1 /* 2 * Copyright (c) 2017 Baidu, Inc. All Rights Reserve. 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 package com.baidu.fsg.uid.utils; 17 18 import java.util.concurrent.atomic.AtomicLong; 19 20 /** 21 * Represents a padded {@link AtomicLong} to prevent the FalseSharing problem<p> 22 * 23 * The CPU cache line commonly be 64 bytes, here is a sample of cache line after padding:<br> 24 * 64 bytes = 8 bytes (object reference) + 6 * 8 bytes (padded long) + 8 bytes (a long value) 25 * 26 * @author yutianbao 27 */ 28 public class PaddedAtomicLong extends AtomicLong { 29 private static final long serialVersionUID = -3415778863941386253L; 30 31 /** Padded 6 long (48 bytes) */ 32 public volatile long p1, p2, p3, p4, p5, p6 = 7L; 33 34 /** 35 * Constructors from {@link AtomicLong} 36 */ 37 public PaddedAtomicLong() { 38 super(); 39 } 40 41 public PaddedAtomicLong(long initialValue) { 42 super(initialValue); 43 } 44 45 /** 46 * To prevent GC optimizations for cleaning unused padded references 47 */ 48 public long sumPaddingToPreventOptimization() { 49 return p1 + p2 + p3 + p4 + p5 + p6; 50 } 51 52 }