LongAdder,LongAccumulator类了解
AtomicLong 通过cas提供了非阻塞的api,但是并发量高的时候,cas会导致大量线程自旋从而浪费cpu资源,所以开发者发明了LongAdder来减少自旋 ...
AtomicLong 通过cas提供了非阻塞的api,但是并发量高的时候,cas会导致大量线程自旋从而浪费cpu资源,所以开发者发明了LongAdder来减少自旋 ...
ThreadLocalRandom原理解析 了解Random类 作用 用来获取随机数,提供nextInt(),nextLong()…api获取随机数 方法解析 先看一段代码 Random random = new Random(); for (int i = 0; i < 10; i++) { // 输出0~5的数 System.out.println("random = " + random.nextInt(5)); } 上面的意思就是循环10次,每次都是调用random对象的nextInt(5) 来获取[0,5)之间的数。 再来看下nextInt()方法 ...
并发编程中的锁 乐观锁与悲观锁 公平锁与非公平锁 独占锁与共享锁 什么是可重入锁 自旋锁
伪共享 从字面意思,我一开始理解的有点迷糊,一开始以为在内存中的变量是不可靠的呢,但是不是!它带来的影响是,会造成多线程操作同一个缓存行的变量性能下降,因为同一个缓存行的修改,只能能同时被一个线程修改,这样就失去了多线程的意义 ...
unsafe类 JDK 的此jar包中 的 Unsafe 类提供了硬件级别的原子性操作 ,Unsafe 类中的方法都是native 方法 ,它们使用JNI的方式访问本地 C++实现库。 使用unsafe类 完成copareAndSwap /** * @author ggBall * @version 1.0.0 * @ClassName UnsafeSateTest.java * @Description 获取不到unsafe app类加载器加载不到 unsafe 因为unsafe只允许bootstrap类加载器获取,Unsafe.getUnsafe()里面也做了判断只允许bootstrap类加载器加载 * @createTime 2022年04月30日 16:44:00 */ public class UnsafeSateTest { static final Unsafe unSafe = Unsafe.getUnsafe(); static long stateOffset = 0; private volatile long state = 0; static { try { // 拿到 属性state在类UnsafeSateTest的偏移量 stateOffset = unSafe.objectFieldOffset(UnsafeSateTest.class.getDeclaredField("state")); } catch (NoSuchFieldException e) { e.printStackTrace(); } } public static void main(String[] args) { UnsafeSateTest unsafeSateTest = new UnsafeSateTest(); boolean result = unSafe.compareAndSwapLong(unsafeSateTest, stateOffset, 0, 1); System.out.println("result = " + result); } } /** * @author ggBall * @version 1.0.0 * @ClassName UnsafeSateTest.java * @Description 利用反射获取unsafe * @createTime 2022年04月30日 16:44:00 */ public class UnsafeSateTest2 { static Unsafe unSafe; static long stateOffset = 0; private volatile long state = 0; static { try { Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); // 获取该变量的值 unSafe = (Unsafe)theUnsafe.get(null); // 拿到 属性state在类UnsafeSateTest的偏移量 stateOffset = unSafe.objectFieldOffset(UnsafeSateTest2.class.getDeclaredField("state")); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } public static void main(String[] args) { UnsafeSateTest2 unsafeSateTest = new UnsafeSateTest2(); boolean result = unSafe.compareAndSwapLong(unsafeSateTest, stateOffset, 0, 1); System.out.println("result = " + result); }