Thread-safe Atomic wrapper classes Example

Source: Internet
Author: User

Refer to an example first http://www.cnblogs.com/aigongsi/archive/2012/04/01/2429166.html#!comments

Even if it is just i++, it is actually composed of multiple atomic operations: Read I, Inc., write I, if multiple threads are executing simultaneously i++,volatile can only guarantee that the I that they operate is the same piece of memory, but it is still possible to write dirty data. If you add atomic wrapper classes with Java 5, you do not need sychronized for operations such as their increase.

Using Atomicinteger, it encapsulates the atomic operations of some integers and makes them thread-safe

 Packagethreadtest;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.TimeUnit;ImportJava.util.concurrent.atomic.AtomicInteger; Public classAtomicIntegerTestApp1 { Public StaticAtomicinteger count =NewAtomicinteger (0);  Public Static voidInc () {//count++;Count.incrementandget (); }     Public Static voidMain (string[] args)throwsinterruptedexception {executorservice service=Executors.newfixedthreadpool (Integer.max_value);  for(inti = 0; I < 10000; i++) {Service.execute (NewRunnable () {@Override Public voidrun () {threadpooltestapp1.inc ();        }            });        } service.shutdown (); //give a close time (timeout), but the actual shutdown time should be this smallService.awaittermination (300, Timeunit.seconds); System.out.println ("Run Result: counter.count=" +threadpooltestapp1.count); }}

Atomic operations in Java include the following:
1) Assignment operation of basic types except long and double
2) All assignment operations that reference reference
3) java.concurrent.atomic.* All operations of all classes in the package
Count++ is not an atomic operation, it is a combination of 3 atomic operations
1. Read the Count value in main memory and assign the value to a local member variable TMP
2.tmp+1
3. Assign TMP to count

Thread-safe Atomic wrapper classes Example

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.