Reputation: 383
I am studying Java concurrency right now. I have a question about synchronized
and locks.
For any mutable data, we should put all the method accessing the data in the same lock.
But, what does same lock mean?
Example:
public class SynchronizedInteger{
private int value;
public synchronized int get(){return value;}
public synchronized void set(int value){this.value=value;}
}
So, my question is why this two methods are in the same lock? I know they are, but I would like to know why? And, does it mean that all the synchronized methods in the class are in the same lock?
Edit:
so, if I added one more method to the class:
public synchronized void printOneToHunder(){
for(int i=0;i<100;i++) System.out.println(i);
}
This method will also be included into same block as setter and getter? So, other thread cannot run this method when there is one thread using either setter or getter?
And, what if I change the class to below:
public class SynchronizedInteger{
private int value1;
private int value2;
public synchronized int get1(){return value1;}
public synchronized void set1(int value){this.value1=value1;}
public synchronized int get2(){return value2;}
public synchronized void set2(int value){this.value2=value2;}
}
For my understanding right now, only one thread can call these method at one time. So what's the way to make one thread can modify value1 and the other thread to modify value2???
Thanks a lot for your kindly clarifications!!!!
Upvotes: 2
Views: 1053
Reputation: 71
But you have other ways for synchronization.
Synchronized blocks:
synchronized(someLockedObj){somecode}
Lock-Objects:
Lock lock = new ReentrantLock(); lock.lock(); lock.unlock();
Upvotes: 0
Reputation: 234847
When you declare a method synchronized
, it means that synchronization is on the particular instance for which the method is being invoked.
Upvotes: 0
Reputation: 206831
All non-static methods that you declare synchronized
behave essentially as if the code was:
public synchronized int get() {
synchronized(this) {
// the method code
}
}
i.e. there is an implicit lock on this
taken. So all non-static synchronized methods will lock the instance on which they are called.
Static synchronized methods take a lock on the class object itself, rather than an instance of that class.
Upvotes: 5
Reputation: 178481
Yes, your two methods are using the same lock.
The synchronized
keyword without parameter is implicitly translated to syncrhonized(this)
, which is the same object for both methods.
In order for two blocks to have "the same lock" in java, it means that they are both using the same object as a lock. And as I said, in your case, both methods are using this
as the lock object.
Upvotes: 4