Is this heart rate detection method thread safe and consistent?

This issue was discussed in two blogs ( http://dow.ngra.de/2008/10/27/when-systemcurrenttimemillis-is-too-slow/ , http://dow.ngra.de/2008/10/28/ what-do-we-really-know-about-non-blocking-concurrency-in-java / ), but I haven't heard the final answer yet. If we have one thread that does this:

public class HeartBeatThread extends Thread {
  public static int counter = 0;
  public static volatile int cacheFlush = 0;

  public HeartBeatThread() {
    setDaemon(true);
  }

  static {
    new HeartBeatThread().start();
  }

  public void run() {   
    while (true) {     
      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }

      counter++;
      cacheFlush++;
    }
  }
}

And many clients who run the following:

if (counter == HeartBeatThread.counter) return;
counter = HeartBeatThread.cacheFlush;

is it thread safe or not?

+3
source share
2 answers

In the model java-memory model? No, you're not alright.

" ", , .

' '

http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7

"" 17.4.2. , - . , "-". , .. . .

, , , , , /, / .

, - undefined, , , . , , , , undefined.

, , - .

java x86 x86-64? , x86 , / , , , . , , , - .

, , ia64? .

java . , , , .

CLR, , , , , .

+5

, , .

if:

if (counter == HeartBeatThread.counter) 
    return;

. , .

: ", A, volatile field f, B, f". B () f (= cacheFlush). HeartBeatThread.counter .

+1

Source: https://habr.com/ru/post/1699302/


All Articles