Syncronization

Syncronization

Why would you use a synchronized block vs. synchronized method?
View Answers

October 26, 2010 at 12:13 PM

Hi,

Here is the answer.

For achieving Multithreading mechanism in java we should go for synchronization. And this can be done in two ways depending on the requirement.

  1. Synchronized block and
  2. Synchronized method.

if you go for synchronized block it will lock a specific object.

if you go for synchronized method it will lock all the objects.

in other way Both the synchronized method and block are used to acquires the lock for an object. But the context may vary. Suppose if we want to invoke a critical method which is in a class whose access is not available then synchronized block is used. Otherwise synchronized method can be used.

Synchronized methods are used when we are sure all instance will work on the same set of data through the same function Synchronized block is used when we use code which we cannot modify ourselves like third party jars etc.

The given code helps you to understand.

class Test1 {

    public void method1() {
        System.out.println("synchronized block example ");

    }
}

public class B {
    public static void main(String s[]) {
        Test1 objecta = new Test1();
        Test1 objectb = new Test1();
        synchronized (objecta) {
            objecta.method1();
        }
        objectb.method1(); // not synchronized
    }
}

Example for synchronized method.

class Test1 {

    public synchronized void method1() {
        System.out.println("synchronized method example");

    }
}

public class B {
    public static void main(String s[]) {
        Test1 objecta = new Test1();
        Test1 objectb = new Test1();
        objecta.method1();
        objectb.method1();
    }
}

Thanks.









Related Tutorials/Questions & Answers:
Syncronization

Ads