Sunday, 15 June 2014

java - Synchronized blocks with static attribute vs shared attributes vs synchronized method -



java - Synchronized blocks with static attribute vs shared attributes vs synchronized method -

i tested 3 versions of same problem, expecting provide perfect synchronization:

1) using static variable lock:

public class synchronizedincrement implements runnable { private static int x = 0; private object o = new object(); public void run() { (int i=0; i<10000; ++i) synchronized(o) { ++x; } } }

2) using same object lock, passed argument in constructor:

public class synchronizedincrement implements runnable { private static int x = 0; private object o = null; public synchronizedincrement(object o) { this.o = o; } public void run() { (int i=0; i<10000; ++i) synchronized(o) { ++x; } } }

3) declaring run() synchronized method:

public synchronized void run() { (int i=0; i<10000; ++i) ++x; }

i using fixed thread pool of 100 threads tests:

public static void main(string[] args) { executorservice es = executors.newfixedthreadpool(100); //object obj = new object(); // used argument sec version (int i=0; i<100; ++i) es.submit(new thread(new synchronizedincrement())); es.shutdown(); while (!es.isterminated()); system.out.println(x); }

outputs version 1, 2 , 3:

560126 1000000 976082

only sec 1 returns expected result. why other 2 fail?

the first code utilize reference o object monitor synchronization. object o different object each instance of synchronizedincrement each thread lock own monitor, allowing them run in parallel incrementing static variable x inconsistently.

the sec implementation utilize object passed argument constructor lock thread. have single reference (obj) you're passing threads in case synchronization done on same object incrementing static variable x consistently.

the lastly piece of code synchronize on "this" (itself) behaves identically first version.

a usual design, maintain info accessed multiple thread encapsulated in different class , synchronize interface methods class.

here, tradeoff have method incx() , declare that:

static synchronized void incx(){ x++; }

in case, run methods don't need synchronized.

java multithreading synchronization

No comments:

Post a Comment