简体   繁体   中英

About java volatile array

I have a problem about volatile arrays. On the internet most people say that the elements of an array are not guaranteed to be volatile, only its reference is. So I write some code to check for it. The result is, it turns out, that it works.

I'm using Windows 10 + JDK 8

My code:

static volatile boolean[] keepRunnin g= { true };

public static void main(String[] args) throws Exception {

    new Thread(
        ()->{
            while (keepRunning[0]){}
        }
    ).start();

    Thread.sleep(1000);

    keepRunning[0] = false;
}

The loop always ends, it's not an infinite loop.

Can anyone explain it?

It is impossible to write code to prove that the elements in the array will always be visible to all threads when they should be.

Your example may demonstrate that it circumstantially works for you (I haven't run it) but you cannot be certain that it will work on all hardware, for all users, all of the time.

It is only possible to write code which disproves that something has visibility across threads. It is impossible to write code which proves it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM