package Paradigms.List11.CommonStaticVariableResolvings;
public class IntCellDefault {
public int getN(){
return n;
}
public void setN(int n){
this.n = n;
}
private int n = 0;
}
class Count extends Thread{
static IntCellDefault n = new IntCellDefault();
@Override
public void run(){
for (int i = 0; i < 200000; i++){
int temp = n.getN();
n.setN(temp+1);
}
}
public static void main(String[] args){
Count thread1 = new Count();
Count thread2 = new Count();
thread1.start();
thread2.start();
try{
thread1.join();
thread2.join();
}catch(InterruptedException e){
System.out.println(e.getStackTrace());
System.out.println("Catched exception");
}
System.out.println("The value of n is " + n.getN());
}
// First of all thread1 and thread2 starts in various times
// Secondly each thread makes a copy to their local caches
// It implies that when thread1 modifies the static variable
// The thread2 can contain old value of static variable
// And will increase basing on old value
// Then finally cause that the value of n.n has lower value then expected 400000
//
// Exception
// InterruptedException is cought for the security because JVM can sometimes throw it
// But common situation is when someone will call interrupt(przerwij) on this thread
//
// Join
// Wait for this thread to die
}
{"html5":"htmlmixed","css":"css","javascript":"javascript","php":"php","python":"python","ruby":"ruby","lua":"text\/x-lua","bash":"text\/x-sh","go":"go","c":"text\/x-csrc","cpp":"text\/x-c++src","diff":"diff","latex":"stex","sql":"sql","xml":"xml","apl":"apl","asterisk":"asterisk","c_loadrunner":"text\/x-csrc","c_mac":"text\/x-csrc","coffeescript":"text\/x-coffeescript","csharp":"text\/x-csharp","d":"d","ecmascript":"javascript","erlang":"erlang","groovy":"text\/x-groovy","haskell":"text\/x-haskell","haxe":"text\/x-haxe","html4strict":"htmlmixed","java":"text\/x-java","java5":"text\/x-java","jquery":"javascript","mirc":"mirc","mysql":"sql","ocaml":"text\/x-ocaml","pascal":"text\/x-pascal","perl":"perl","perl6":"perl","plsql":"sql","properties":"text\/x-properties","q":"text\/x-q","scala":"scala","scheme":"text\/x-scheme","tcl":"text\/x-tcl","vb":"text\/x-vb","verilog":"text\/x-verilog","yaml":"text\/x-yaml","z80":"text\/x-z80"}