Source: Hi learning network sensitive and eager Forum www.piaodoo.com welcome to learn from each other
First look at the two pieces of code, some are Integer, and some are AtomicInteger, the following:
public class Sample1 { private static Integer count = 0; synchronized public static void increment() { count++; } }
The following are AtomicInteger of:
public class Sample2 { private static AtomicInteger count = new AtomicInteger(0); public static void increment() { count.getAndIncrement(); } }
More than two pieces of code, when using Integer, the situation must be added to ensure synchronized concurrent threads access does not appear, but not in the AtomicInteger plus synchronized, here AtomicInteger provide atomic operations, this would be the following the appropriate introduction.
Introduction AtomicInteger
AtomicInteger provide an atomic operation Integer class, addition and subtraction operation by a thread-safe manner.
AtomicInteger usage scenarios
AtomicInteger provides atomic operations performed using Integer therefore very suitable for use at high concurrency.
AtomicInteger part explain the source
public class AtomicInteger extends Number implements java.io.Serializable { private static final long serialVersionUID = 6214790243416807050L; // setup to use Unsafe.compareAndSwapInt for updates private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; static { try { valueOffset = unsafe.objectFieldOffset (AtomicInteger.class.getDeclaredField("value")); } catch (Exception ex) { throw new Error(ex); } } private volatile int value;
The above is part of the source code AtomicInteger, said here under which the value, where value using the volatile keyword, volatile action can be done here is to make multiple threads can share variables, but the problem is the use of volatile will make VM optimization out of action, resulting in lower efficiency, to be used when necessary, and therefore not free to use AtomicInteger class, to be used in the usage scenarios.
AtomicInteger instance
The following is in multithreading, use one instance of AtomicInteger, this code is borrowed from the IT house in a piece of code.
AtomicTest class {public static Long randomtime () { return (Long) (Math.random () * 1000); } public static void main (String [] args) { // blocking queue file 100 can accommodate final BlockingQueue <File > = new new Queue a LinkedBlockingQueue <File> (100); // thread pool Final Executors.newFixedThreadPool ExecutorService Exec = (. 5); Final the root File = new new File ( "D: \\ the ISO"); // completion flag final File exitFile File new new = ( ""); // integer atoms, the number of read // AtomicInteger atomization can be achieved concurrent update in case, to avoid the use of the synchronized, and the performance is very high. of AtomicInteger of AtomicInteger new new RC = Final (); // Integer atoms, the number of write Final of AtomicInteger of AtomicInteger new new WC = (); // read thread Read the Runnable new new = the Runnable () { public void RUN () { ScanFile (the root); ScanFile (exitFile); } public void ScanFile (File File) { IF (file.isDirectory ()) { File [] = File.listFiles Files (the FileFilter new new () { public Boolean Accept (File pathname) { return pathname.isDirectory () || pathname.getPath () endsWith ( "ISO.");. } }); for (File One: Files) ScanFile (One ); } {the else the try { incrementAndGet method integer // atoms, atoms to the current value plus 1, the return value is updated int index = rc.incrementAndGet (); System.out.println ( "read0:" + index + "" + file.getPath ()); // add to the blocking queue queue.put (File); } the catch (InterruptedException E) { } } } }; / / submit to submit a method Runnable task for execution and returns a Future representing that task. exec.submit (Read); // write four threads for (int index = 0; index <. 4; index ++) { // Write Thread Final NUM = int index; the Runnable new new = Write the Runnable () { String threadName = "the Write "+ NUM; public void RUN () { the while (to true) { the try { the Thread.sleep (randomtime ()); Method incrementAndGet integer // atoms, atoms to the current value plus 1, updates the value of the return int index = wc.incrementAndGet (); // Get and removes the head of this queue, before the element has been made available wait (if necessary). File = queue.take File (); // queue has no target IF (File == exitFile) { // add again "flag" to allow other threads to normal exit queue.put (exitFile); BREAK; } System.out .println (threadName + ":" + index + "" + file.getPath ()); } the catch (InterruptedException E) { } } } }; exec.submit (Write); } exec.shutdown (); } }
AtomicInteger use summary
AtomicInteger is nonblocking concurrency control algorithm, in some very high for concurrent programs, but are not suitable for each scene, to be used in different scenarios using different values of the class.
That's all for this article on how to use Java AtomicInteger Detailed class, and we want to help. Interested friends can see: java native serialization and serialization performance Kryo instance comparative analysis on the development of Java enterprise project ideas, Java map storage array and the value of the code Detailed out and so on, have any questions you can leave a message at any time, Xiao Bian will promptly reply to everyone.
The original address is: http: //www.piaodoo.com/thread-13234-1-2.html stockings control www.txdah.com 131 outside www.buzc.org enjoyable learning can help to learn better!