CAS--campareAndSet
自定义异常
package com.dwz.atomicApi; public class GetLockException extends Exception { public GetLockException() { super(); } public GetLockException(String message) { super(message); } }
自定义锁
package com.dwz.atomicApi; import java.util.concurrent.atomic.AtomicInteger; public class CompareAndSetLock { private final AtomicInteger value = new AtomicInteger(0); //保证锁是由同一个线程释放 private Thread lockedThread; public void tryLock() throws GetLockException { boolean success = value.compareAndSet(0, 1); if(!success) { throw new GetLockException("Get the lock failed!"); } else { lockedThread = Thread.currentThread(); } } public void unlock() { if(0 == value.get()) { return; } if(lockedThread == Thread.currentThread()) { value.compareAndSet(1, 0); } } }
测试代码
package com.dwz.atomicApi; /** * synchronized在加锁后如果当前业务执行时间太长,后面的对象抢不到锁会一直等待 * 在此我们加一个快速失败的场景,使用CAS自定义的一个显示锁 */ public class AtomicIntegerDetailsTest2 { private final static CompareAndSetLock lock = new CompareAndSetLock(); public static void main(String[] args) { for(int i = 0; i < 5; i++) { new Thread() { @Override public void run() { try { doSomething2(); } catch (InterruptedException e) { e.printStackTrace(); } catch (GetLockException e) { e.printStackTrace(); } }; }.start(); } } private static void doSomething() throws InterruptedException { synchronized (AtomicIntegerDetailsTest2.class) { System.out.println(Thread.currentThread().getName() + " get the lock"); Thread.sleep(100000L); } } private static void doSomething2() throws InterruptedException, GetLockException { try { lock.tryLock(); System.out.println(Thread.currentThread().getName() + " get the lock"); Thread.sleep(100000L); } finally { lock.unlock(); } } }
附加:
CAS轻量级锁,带来一个严重问题,ABA问题