When we use a synchronized keyword, what is being blocked?
The question comes to my mind when we read about concurrency issues in threads and deal with it with a keyword synchronized
, since when the term lock
is used it is used for an object that contains a run
method (or a thread job). But why can't we just use the term lock
for a method whose definition contains a keyword synchronized
, since that keyword means that after a thread enters that method, that thread might be broken by the JVM scheduler after the method ends?
I study from the first chapter of java, and there is a line that "the object is locked", and the given reason again repeats the question, "what happens if we have two synchronized methods". So I'm confused here, what is the amazing thing that can happen if only the method is blocked?
Please forgive me if I asked a vague question and thanks in advance.
source to share
Using the sync keyword is the implicit equivalent of using ReentrantLock , as the javadoc shows in the example:
class X {
private final ReentrantLock lock = new ReentrantLock();
// ...
public void m() {
lock.lock(); // block until condition holds
try {
// ... method body
} finally {
lock.unlock()
}
}
}
I don't know if it will answer your question, maybe I should make a juste comment.
source to share
The solution to your question is: what happens if we have two synchronized methods?
Consider the following piece of code: -
public class Worker {
private Object lock1 = new Object();
private Object lock2 = new Object();
public void step1() {
synchronized (lock1) {
//do something
}
}
public void step2() {
synchronized (lock2) {
//do something
}
}
public void process() {
step1();
step2();
}
public void main() {
long start = System.currentTimeMillis();
Thread t1 = new Thread(new Runnable() {
public void run() {
process();
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
public void run() {
process();
}
});
t2.start();
t1.join();
t2.join();
long end = System.currentTimeMillis();
System.out.println("time taken " + (end - start));
}
}
In this code snippet, we use lock1 and lock2 as object locks, but what happens if we use the this keyword instead of these locks (lock1 and lock2)?
- time without using this keyword (using lock1, lock2 as above) = T
- the time used with this keyword in both synchronized blocks = 2T,
This time difference occurs because the same object lock is used in both synchronized blocks. If thread-1 calls step1, step2 will block for thread-2. If the method is independent, different locks should be used.
source to share