Make delicious recipes!

Synchronized

Synchronized method and synchronized block with monitor => these are equivalent for non-static functions that means both make threads wait when they try to access code for same object.

If objects are different, threads are not blocked.



So following 2 are same:


public synchronized void foo () {
    // do something
}


public void foo () {
    synchronized (this) {
        // do something
    }
}

However, if you add static to both the functions, then its semantic changes and they no longer remain equivalent.


public static synchronized void foo () {
    // do something
}


public static void foo () {
    synchronized (this) {
        // do something
    }
}


Here, first functions becomes synchronized at class level whereas second one is still at object level. So even if the objects are different, first function makes accessing threads wait while second function allows for such case. If object is same, then obviously both functions block.







Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal