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理解为一个快照。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值