java.lang.Number家族(源码学习)

  1. java.lang.Number这个基础类,看似貌不惊人,其实在java数字类型生态系统中很重要。上图看下他的子类家族     基本涵盖了咱们经常使用的几个数字类型的封装类,Byte、Double、Float、Integer、Long、Short,还有Atomic家族,AtomicDouble、AtomicInteger、AtomicLong
  2. 再看看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();
    }
    因此,咱们记住,只要继承自Number类型全部子类,所有包含以上几个方法。
  3. 咱们再来看下各个实现类关于intValue()方法的实现原理。其中,Double、Float、Integer等线程不安全类型实现方式是相同的,
    private final int value;
       public Integer(int value) {
    	this.value = value;
        }
       public int intValue() {
    	return value;
       }
    为何使用final修饰?设计者的目的是在构造的时候赋值,且在后边不会也不容许再修改该变量的值。
  4. 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; }
  5. 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理解为一个快照。