Questions about volatile visibility and disallow Command Re-sorting, volatile sorting

Source: Internet
Author: User

Questions about volatile visibility and disallow Command Re-sorting, volatile sorting

In the test of learning volatile semantics visibility and prohibiting Command Re-sorting, it is found that the feature of prohibiting Command Re-sorting cannot be reflected.

 

The experiment code is as follows:

Package com. aaron. beginner. multithread. volatiletest; import java. util. concurrent. countDownLatch;/*** @ author * @ description describes the object's purpose in one sentence * @ date */public class VolatileAndNonVolatileTest {privateVolatileBoolean flag; private int num; public static void main (String [] args) throws InterruptedException {for (int I = 0; I <5000; I ++) {final VolatileAndNonVolatileTest test = new VolatileAndNonVolatileTest (); CountDownLatch latch = new CountDownLatch (2); Thread write = new Thread ()-> {test. write (); latch. countDown () ;}); Thread read = new Thread ()-> {test. read (); latch. countDown () ;}); write. start (); read. start (); latch. await () ;}} private void read () {if (flag) {System. out. println ("=" + num * num) ;}} private void write () {num = 10; // Step 1 flag = true; // Step 2 }}

 

Tutorial steps:

Pay attention to the flag variables in the Code and test the output of the flags with volatile modification and without volatile modification respectively.

 

Main functions of this test code:

Tutorial steps:

Expected results:

Actual results:

That is, the result is consistent with that without volatile.

 

Do you know how to test this volatile, which demonstrates the features and visibility of prohibiting Command Re-sorting?

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.