synchronized block doesn't lock the object

java, multithreading

Solution

By doing this

_c++

you are changing the reference that `_c` is holding. It is equivalent to

int value = _c.intValue();
_c = Integer.valueOf(value + 1);

Therefore

synchronized (_c) {

each time synchronizes on a different object.

Remember, a `synchronized` block locks on an object, not a variable.

You should always use `synchronized` with a variable that cannot change values, ie. make it `final`.

If you need a counter for some reason, consider using `AtomicInteger`.

Problem

Someone explain, why doesn't `synchronized block` lock the variable `_c` here? ``` public class static_thread implements Runnable{ private static Integer _c=0; public static void main(String[] args) throws Throwable { for(int i=0;i<100000;i++){ if(i%2==0){_c++;} } System.out.println("one thread: "+_c); Thread[] t=new Thread[50]; _c=0; for(int i=0;i<t.length;i++){ t[i]=new Thread(new static_thread(i, i*(100000/50))); t[i].start(); } for(Thread _:t){_.join();} System.out.println("+one thread: "+_c);//wrong answer! } public void run() { for(int i=s;i<(s+l);i++){ if(i%2==0){ synchronized (_c) {//y u no lock?! _c++;//Inconsistence, not thread-safe, so what is synchronized block is doing here? } } } } int s,l; public static_thread(int s, int l) { this.s = s; this.l = l; } } ``` for each run, I get new wrong value.

Original source