java - Why static variable is shared among the threads -


in posts have read -

if 2 threads(suppose thread 1 , thread 2) accessing same object , updating variable declared static means thread 1 , thread 2 can make own local copy of same object(including static variables) in respective cache, updating thread 1 static variable in local cache wont reflect in static variable thread 2 cache . static variables used in object context updating 1 object reflect in other objects of same class not in thread context updating of 1 thread static variable reflect changes threads (in local cache).

but when run below code snippet

public class statcivolatile3 {      public static void main(string args[]) {         new examplethread2("thread 1 ").start();         new examplethread2("thread 2 ").start();     }  }  class examplethread2 extends thread {     private static int testvalue = 1;      public examplethread2(string str) {         super(str);     }      public void run() {         (int = 0; < 3; i++) {             try {                 system.out.println(getname() + " : " + i);                 if (getname().compareto("thread 1 ") == 0) {                     testvalue++;                     system.out.println("test value t1: " + testvalue);                 }                 if (getname().compareto("thread 2 ") == 0) {                     system.out.println("test value t2: " + testvalue);                 }                 thread.sleep(1000);             } catch (interruptedexception exception) {                 exception.printstacktrace();             }         }     } } 

the output -

thread 1  : 0 thread 2  : 0 test value t2: 2 test value t1: 2 thread 2  : 1 test value t2: 2 thread 1  : 1 test value t1: 3 thread 2  : 2 test value t2: 3 thread 1  : 2 test value t1: 4 

as static variable not shared among threads thread 2 test value should 1. not case.

i read many other questions related same problem still not able understand why happening. please me in understanding problem.

thanks in advance.

i think you're being confused dangers of memory model.

static variables are shared between threads - articles you've been reading haven't been trying each thread has own independent set of static variables. instead, they've been trying inform unprotected modification of shared state isn't guaranteed visible in other threads without setting appropriate memory barriers. it's entirely fine changes visible other threads - it's not guaranteed.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -