AtomicInteger In Java

What can AtomicInteger do for you?

The AtomicInteger class provides you with a int variable which can be read and written actomically.You can create an AtomicInteger with the initial value 0 like this:

AtomicInteger atomicInteger = new AtomicInteger();

If you want to create an AtomicInteger with an initial value,you can do so like this:

AtomicInteger atomicInteger = new AtomicInteger(123);

Set() method

You can set the value of an AtomicInteger instance via the set() method:

atomicInteger.set(235);

compareAndSet() method

The AtomicIngeter class also has an atomic compareAndSet() method.For example:

AtomicInteger atomicInteger = new AtomicInteger(123);
int expectedValue = 123;
int newValue = 555;
atomicInteger.compareAndSet(expectedValue,newValue);

This example first creates an AtomicInteger instance with an initial value of 123.Then it compares the value of the atomicInteger to expectedValue and if they are equal ,the new value of the atomicInteger becomes 555.

Other methods to add a value to the AtomicInteger

  • addAndSet():adds a number to the AtomicInteger and returns its value after the addition.
  • getAndAdd():adds a number to the AtomicInteger but returns the value the AtomicInteger had before the value was added.
  • getAndIncrement(): adds 1 to the value of the AtomicInteger,inside the method,it returns getAndAddInt(this,VALUE,1)
  • incrementAndGet():adds 1 to the value of the AtomicInteger,inside the method,it returns getAndAddInt(this,VALUE,1)+1

Subtracting from the AtomicInteger Value

The AtomicInteger class also contains a few methods for subtracting values from the AtomicInteger value atomically.

  • decrementAndGet():It actually returns "getAndAddInt(this,VALUE,-1) -1"
  • getAndDecrement():It actually returns "getAndAddInt(this,VALUE,-1)"

Most of the developers know the benefits of threads(responsiveness,exploiting,multicores,etc),most of them also know the risks of threads(data inconsistency,deadlock,context switch overhead,etc).

Thread synchronization is needed when multiple threads access some changeable data and one of them might change it.

Synchronization provided in java enables us to enforce two things:atomicity and visibility.

When you want to change an Integer variable between threads,beside using synchronized key word,you can use AtomicIngeter class to achieve it.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值