使用CAS代替synchronized

x33g5p2x  于2022-02-14 转载在 其他  
字(1.3k)|赞(0)|评价(0)|浏览(396)

在开发当中需要经常用到synchronized保证代码线程安全,在竞争条件下会阻塞等待资源,如果允许竞争不到资源返回失败,就可以使用cas减少阻塞时间。先来看一个cas的单例模式。

public class NonBlock {
 
	private static volatile NonBlock nonBlock;
 
	private static AtomicBoolean atomicBoolean = new AtomicBoolean(false);
 
	public static NonBlock getInstance() {
		if (nonBlock == null) {
			if (atomicBoolean.compareAndSet(false, true)) {
				nonBlock = new NonBlock();
			}
		}
		return nonBlock;
	}
}

在这个单例模式中,不同于synchronized的阻塞,多线程环境下,getInstance确保只会创建一个对象的情况下,可能返回的nonBlock是一个空对象。但,如果允许返回空对象的情况下,

public class RedPacket {
 
		private long balance;
 
		private int num;
 
		public RedPacket(long balance, int num) {
			this.balance = balance;
			this.num = num;
		}
 
		public long get() {
			if (balance < 1 || num < 1) {
				return -1;
			}
			if (num == 1) {
				long result = balance;
				balance = 0;
				num--;
				return result;
			}
			long average = balance / num;
			long result = ThreadLocalRandom.current().nextLong(1, average * 2);
			balance -= result;
			num--;
			return result;
		}

我们还可以使用cas达到非阻塞的目的,这样能保证线程安全,出现竞争情况就提示抢失败,确点就是提示抢失败还可能余额大于0,先来不一定能抢到,后来人还能抢。

public class RedPacket {
 
		private long balance;
 
		private AtomicInteger num;
 
		public RedPacket(long balance, int num) {
			this.balance = balance;
			this.num = new AtomicInteger(num);
		}
 
		public long get() {
			int number = num.get();
			long balan = balance;
			if (balan < 1 || number < 1) {
				return -1;
			}
			if (num.compareAndSet(number, number - 1)) {
				if (number - 1 == 0) {
					balance = 0;
					return balan;
				}
				long average = balan / number;
				long result = ThreadLocalRandom.current().nextLong(1, average * 2);
				balance -= result;
			}
			return -1;
		}
	}

相关文章