乐观锁与悲观锁

来源:互联网 发布:ip地址修改软件 编辑:程序博客网 时间:2024/05/22 16:50

1.解释

          独占锁是一种悲观锁,synchronized就是一种独占锁,它假设最坏的情况,并且只有在确保其它线程不会造成干扰的情况下执行,会导致其它所有需要锁的线程挂起,等待持有锁的线程释放锁。而另一个更加有效的锁就是乐观锁。所谓乐观锁就是,每次不加锁而是假设没有冲突而去完成某项操作,如果因为冲突失败就重试,直到成功为止。


1.1乐观锁的实例

Java 1.6中AtomicLong.incrementAndGet()的实现源码为:

AtomicLong.incrementAndGet的实现用了乐观锁技术,调用了sun.misc.Unsafe类库里面的 CAS算法,用CPU指令来实现无锁自增。所以,AtomicLong.incrementAndGet的自增比用synchronized的锁效率倍增。


public final int getAndIncrement() {          for (;;) {              int current = get();              int next = current + 1;              if (compareAndSet(current, next))                  return current;          }  }     public final boolean compareAndSet(int expect, int update) {      return unsafe.compareAndSwapInt(this, valueOffset, expect, update);  }

Java 1.7中ConcurrentHashMap的部分源码:
 if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))                == null) { // recheck                Segment<K,V> s = new Segment<K,V>(lf, threshold, tab);                while ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))                       == null) {                    if (UNSAFE.compareAndSwapObject(ss, u, null, seg = s))                        break;                }            }



原创粉丝点击