illustrating volatile : is this code thread-safe?

前端 未结 6 948
感动是毒
感动是毒 2020-12-17 05:49

I\'m trying to illustrate the use and importance of volatile with an example that would really not give a good result if volatile was omitted.

6条回答
  •  情深已故
    2020-12-17 06:55

    Victor is right, there are issues with your code: atomicity and visibility.

    Here's my edition:

        private int count;
        private volatile boolean stop;
        private volatile boolean stopped;
    
        @Override
        public void run() {
            while (!stop) {
                count++; // the work
            }
            stopped = true;
            System.out.println("Count 1 = " + count);
        }
    
        public void stopCounting() {
            stop = true;
            while(!stopped)
               ; //busy wait; ok in this example
        }
    
        public int getCount() {
            if (!stopped) {
                throw new IllegalStateException("not stopped yet.");
            }
            return count;
        }
    
    }
    

    If a thread observes that stopped==true, it's guaranteed that the work completes and the result is visible.

    There is a happens-before relation from volatile write to volatile read (on the same variable), so if there are two threads

       thread 1              thread 2
    
       action A
           |
     volatile write  
                      \
                         volatile read
                              |  
                           action B
    

    action A happens-before action B; writes in A are visible by B.

提交回复
热议问题