1

I have a number of shared variable x,y,z, all of which can modified in two different methods running in two different threads.(say method 1 in thread 1 and method 2 in thread 2) . If I declare these two methods as synchronized , does it guarantee the consistency of the variables x,y and z. Or should I separately use a lock on each of those variables?

6
  • 2
    synchronized is applied on instances not methods.
    – Eng.Fouad
    Nov 25, 2012 at 8:06
  • @Eng.Fouad ... which means that the results will be consistent. Dare to write an answer? Nov 25, 2012 at 8:07
  • @Eng.Fouad: That's true, but you can also declare a method to be synchronized. It inserts an implicit synchronized (this) around the body of the method. Nov 25, 2012 at 8:08
  • Also, you must not only synchronize the code blocks which modify the variables, but also the code blocks which read the variables.
    – JB Nizet
    Nov 25, 2012 at 8:10
  • 1
    Are you describing a single class here? One class containing the variables mentioned and the two methods? Nov 25, 2012 at 8:11

4 Answers 4

2

Yes, your approach will guarantee consistency, assuming those variables are all private and are not accessed (read or write) outside of the two synchronized methods.

Note that if you read those variables outside of a synchronized block then you could get inconsistent results:

class Foo {
    private int x;

    public synchronized void foo() {
        x = 1;
    }

    public synchronized void bar() {
        x = 2;
    }

    public boolean baz() {
        int a = x;
        int b = x;
        // Unsafe! x could have been modified by another thread between the two reads
        // That means this method could sometimes return false
        return a == b;
    }
}

EDIT: Updated to address your comment about the static variable.

Each class should own its own data. If class A allows direct access to a variable (by making it public) then it is not owning its own data and it becomes very difficult to enforce thread safety.

If you do this:

class A {
    private static int whatever;

    public static synchronized int getWhatever() {
        return whatever;
    }

    public static synchronized void setWhatever(int newWhatever) {
        whatever = newWhatever;
    }
}

then you'll be fine.

Remember that synchronized enforces a mutex on a single object. For synchronized methods it's this (or the Class object for static methods). Synchronized blocks on other objects will not interfere.

class A {
    public synchronized void doSomething() {...}
}
class B {
    public synchronized void doSomethingElse() {...}
}

A call to doSomething will not wait for calls to doSomethingElse because they're synchronized on different objects: in this case, the relevant instance of A and the relevant instance of B. Similarly, two calls to doSomething on different instances of A will not interfere.

I highly recommend that you take a look at Java Concurrency in Practice. It is an excellent book that explains all the subtleties of the Java thread and memory models.

7
  • Are you sure? What if each thread instantiates a new Foo? Gotcha? Nov 25, 2012 at 8:28
  • @cameron: Suppose if the foo() method is in class foo and the bar() method is in a different class say class bar. Suppose the variable x is not private and I modify it in both the methods foo() and bar(). Then does it ensure consistency?
    – Ashwin
    Nov 25, 2012 at 8:31
  • @Ashwin No it doesnt. See my answer. Consistency can only be ensured if the lock is obtained on the same object. Nov 25, 2012 at 8:34
  • @bot: Thanks. So what is the solution. Individual locks on the variables?
    – Ashwin
    Nov 25, 2012 at 8:39
  • 1
    @bot: Gotcha? No. If each thread instantiates a new Foo then they won't interfere with each other. x is an instance variable, so if there are different instances of Foo then they each have their own x. There's no need to worry about thread safety if each object is accessed by exactly one thread. Nov 25, 2012 at 10:19
1

Yes it will be consistent.

A synchronized method acquires a monitor (§17.1) before it executes. For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used.

Check out this link

Note:- One point you have to be careful about (several programmers generally fall in that trap) is that there is no link between synchronized static methods and sync'ed non static methods

3
  • Are you sure? What if each thread instantiates a new instance of the class containing the methods the thread will call? Nov 25, 2012 at 8:30
  • 2
    @bot: if that was the case, then the OP wouldn't have shared variables being modified by different threads, as the question says.
    – JB Nizet
    Nov 25, 2012 at 8:34
  • The OP was talking about 2 different instances of 2 diferent classes sharing a variable as opposed to a single instance of a classs being shared with 2 threads. Your answer doesn't address the OP's question and is incorrect as can be justified by my answer. Nov 25, 2012 at 9:24
1

When you synchronize on methods :

  1. If method is static, the lock will be taken on the class object
  2. If method is non-static, the lock will be taken on the instance object.

As long as the lock is taken only by one thread at one time, yes it is consistent and safe to do what you intend to.

0

This is subjective. The behaviour depends on the way you instantiate your threads. If two threads call the synchtonized methods on the same instance of the class containing these methods, they will block. If each thread instantiates a new object of the class containing the methods, they will not block since there will be two locks on two different instances of the class.

11
  • But is blocking bad? Deadlocking certainly is. Invalid reads of variable certainly are! Nov 25, 2012 at 8:21
  • When i say blocking, I mean waiting to acquire the lock. Thats why synchronization was introduced in the first place, to stop threads from jumping around in an unpredictable manner and to avoid race conditions. There wont be any invalid reads if your threads lock on a single instance. Nov 25, 2012 at 8:27
  • @bot: Thanks. So what is the solution. Individual locks on the variables?
    – Ashwin
    Nov 25, 2012 at 8:46
  • 1
    @Bot: "You can't acquire locks on a variable". That's somewhat misleading. The synchronized keyword obtains the monitor for an object. If a method is declared synchronized then it implicitly obtains the monitor for this for the duration of the method. It's perfectly acceptable to have a synchronized block that obtains the monitor for a different variable. Nov 25, 2012 at 10:22
  • 1
    @Bot: This is not subjective, nor does it depend on how the threads are instantiated. The behaviour of synchronized is well-defined in the language spec, and how you obtain the Thread objects is irrelevant. If two threads access different objects then there is no way there can be a race condition or an invalid read. So we only need to consider the case where two threads access the same object. So long as critical sections (i.e. reads/writes to shared data) are protected by synchronization on an appropriate object there will not be a problem. Nov 25, 2012 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.