PROJET AUTOBLOG


Shaarli - Les discussions de Shaarli

Archivé

Site original : Shaarli - Les discussions de Shaarli du 23/07/2013

⇐ retour index

How to demonstrate java multithreading visibility problems? - Stack Overflow

lundi 21 juillet 2014 à 14:10
®om's shaarli, le 21/07/2014 à 14:10
La synchronisation (avec un mutex par exemple) ne sert pas qu'à éviter des accès concurrents sur une section de code, elle permet aussi de synchroniser les caches des threads.

Mais comment le mettre en évidence ? Voici un bout de code Java pour tester :

public class VisibilityTest extends Thread {

   boolean keepRunning = true;

   public static void main(String[] args) throws Exception {
       VisibilityTest thread = new VisibilityTest();
       thread.start();
       Thread.sleep(1000);
       thread.keepRunning = false;
       System.out.println(now() + ": keepRunning is false");
   }

   private static long now() {
       return System.currentTimeMillis();
   }

   @Override
   public void run() {
       System.out.println(now() + ": start");
       while (keepRunning) {}
       System.out.println(now() + ": end");
   }

}

http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html

À tester également en déclarant keepRunning volatile…
(Permalink)