- java.lang.Number这个基础类,看似貌不惊人,其实在java数字类型生态系统中很重要。上图看下他的子类家族
基本涵盖了我们常用的几个数字类型的封装类,Byte、Double、Float、Integer、Long、Short,还有Atomic家族,AtomicDouble、AtomicInteger、AtomicLong
- 再看看Number类中的方法
所以,我们记住,只要继承自Number类型所有子类,全部包含以上几个方法。public abstract int intValue(); public abstract long longValue(); public abstract float floatValue(); public abstract double doubleValue(); public byte byteValue() { return (byte)intValue(); } public short shortValue() { return (short)intValue(); }
- 我们再来看下各个实现类关于intValue()方法的实现原理。其中,Double、Float、Integer等线程不安全类型实现方式是相同的,
为什么使用final修饰?设计者的目的是在构造的时候赋值,且在后边不会也不允许再修改该变量的值。private final int value; public Integer(int value) { this.value = value; } public int intValue() { return value; }
- Atomic家族intValue实现方式
private volatile long value; public AtomicLong(long initialValue) { value = initialValue; } public final long get() { return value; }<pre name="code" class="java">public int intValue() { return (int)get(); }
①这个是AtomicLong类型的intValue方法实现原理,可以看到使用了volatile关键字修饰了value,使用valotile目的是强制cpu线程缓存同步,防止脏读,②我们注意到value没有用final修饰,是因为Atomic类型还有一个set方法,public final void set(long newValue) { value = newValue; } - Atomic原子性实现原理,先来看下AtomicLong源码
/** * Atomically sets to the given value and returns the old value. * * @param newValue the new value * @return the previous value */ public final long getAndSet(long newValue) { while (true) { long current = get(); if (compareAndSet(current, newValue)) return current; } } /** * Atomically sets the value to the given updated value * if the current value {@code ==} the expected value. * * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(long expect, long update) { return unsafe.compareAndSwapLong(this, valueOffset, expect, update); }
Atomically sets to the given value and returns the old value.这个注解说的很清楚,设置为新值,返回设置之前的值,方法中写了一个while循环,调用native方法unsafe.compareAndSwapLong(this, valueOffset, expect, update),大名鼎鼎的cas原子操作!我们看到“valueOffset”这个参数,意思是如果valueOffset位置包含的值与expect值相同,则更新valueOffset位置的值为update,并返回true,否则不更新,返回false。可以把valueOffset理解为一个快照。