使用CAS代替synchronized

在开发当中需要经常用到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是一个空对象。但,如果允许返回空对象的情况下, 使用cas性能会比synchronized阻塞要好。

来看另一个例子,抢红包,每次抢红包之前,我们需要锁了RedPacket对象,以此来保证balance和num不会出现负数的情况。

	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;
		}
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值