Java is a very tricky interview questions: i ++ it is thread-safe

Reprinted from   a very tricky Java interview questions: i ++ it is thread-safe

i ++ thread-safe?

I believe that many of the senior Java interviewers have encountered this problem, a lot of this is certainly not very clear face mask to force. Heart certainly still question, i ++ there is still thread-safety issues? Can only say that they know enough, they limited their level.

Consider the following examples to verify at first i ++ in the end is not thread safe.

1000 threads, each of the shared variable count ++ 1000 times operation.


   
   
  1. static int count = 0;
  2. static CountDownLatch cdl = new CountDownLatch( 1000);
  3. /**
  4. * 微信公众号:Java面经
  5. */
  6. public static void main(String[] args) throws Exception {
  7.    CountRunnable countRunnable = new CountRunnable();
  8.     for ( int i = 0; i < 1000; i++) {
  9.         new Thread(countRunnable).start();
  10.    }
  11.    cdl.await();
  12.    System.out.println(count);
  13. }
  14. static class CountRunnable implements Runnable {
  15.     private void count() {
  16.         for ( int i = 0; i < 1000; i++) {
  17.            count++;
  18.        }
  19.    }
  20.     @Override
  21.     public void run() {
  22.        count();
  23.        cdl.countDown();
  24.    }
  25. }

The above example we expected result should be 1,000,000, but run N times, you will find always 1000000, at least now you know i ++ operation it is not thread-safe.

First look at JMM model in principle to read and write to shared variables it.

 

Each thread has its own working memory, each thread must first share when the need for shared variables manipulated variable from main memory to load their working memory, such as when the operation is completed and then save the shared variable to main memory.

The problem lies in that, if a thread is not finished brush operation to main memory, then the value of the shared variable by another thread to read from the main memory, the data read this time the data is dirty, it It will cover the other thread end of the calculation of the value. . .

This is the classic problem of memory is not visible, then let the count plus volatile memory seen whether it can solve this problem?  The answer is: no. Because the volatile can only guarantee visibility, we can not guarantee atomicity. Multiple threads simultaneously read the value of the shared variable, even if other threads modify ensure visibility, there is no guarantee between threads to read the same value then the value of each other's coverage.

Several key concepts about multithreading please refer to " atomicity of multi-threading, visibility, orderly explain " this article.

solution

Having said that, i ++ for this thread insecurity there any other solution? Of course, please refer to the following solutions.

1, a method of operation i ++ plus synchronization lock, while only one thread performs operations i ++;

2, the use of atomic operations support classes, as  java.util.concurrent.atomic.AtomicIntegerit is used CAS algorithm more efficient than the first type;

Guess you like

Origin www.cnblogs.com/jpfss/p/10968243.html