[Android Pro] The use of Atomicinteger

Source: Internet
Author: User

J2SE 5.0 provides a set of atomic classes to help us simplify the synchronization process. The basic working principle is to use the synchronous synchronized method to implement a long, Integer, object increment, Decrement, assignment (update) operation. For example, the + + operator Atomicinteger can increment the integer that it holds atomic. Program code that requires access to two or more atomic variables (or two or more operations on a single atomic variable) usually needs to be synchronize so that both operations can be treated as a atomic unit.

Java Multithreading Usage-use Atomicinteger to see the powerful features of Atomicinteger with a simple comparison of two examples
Class Counter {    private volatile int count = 0;    public synchronized void increment () {           count++;  To perform a thread-safe execution of count++, you need to lock the public    int GetCount () {           return count;    }}
Class Counter {    private Atomicinteger count = new Atomicinteger ();     public void Increment () {           count.incrementandget ();    }       After you use Atomicinteger, you do not need to lock, or you can implement thread safety. public    int GetCount () {          return count.get ();    }}

From the example above we can see that the use of Atomicinteger is very safeSo why not use the register to add, such as count++, because this count is thread insecure, high concurrency access statistics will be wrong, and atomicinteger why can achieve more than chaos, handle high concurrency to cope with it? This is implemented by the hardware-supplied atomic operation instructions. In the case of non-intense competition, the overhead is smaller and faster. The atomic operations classes implemented in Java.util.concurrent include: Atomicboolean, Atomicinteger, Atomiclong, Atomicreference.

[Android Pro] The use of Atomicinteger

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.