Program with synchronized and non-sycnhronized blocks execution - java

I have two methods Synchronized and non-synchronized. Two threads t1 accessing Synchronized method and t2 with non-synchronized method. Will T2 wait till T1 finishes and exits synchronized block? How is this done?

All synchronized blocks synchronized on the same object can only have one thread executing inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.
Only if t1 and t2 are trying to access same synchronized method of same object, then other have to wait until first one finishes it's job. However, this is not case as per your question. See here http://www.geeksforgeeks.org/synchronized-in-java/

Synchronized method will effect only threads using this method, therefore in your case T2 isn't using the method and won't wait for T1
Read more about Synchronized Methods
When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block

Related

how the synchronized keyword lock the method or block using the object

When we want to lock the block by synchronized statements we pass a object to it , I want to know that how this object lock the block , actually I want to know the mechanism of lock by synchronized keyword.
example :
Object object = new Object();
synchronized (object) {
//do something
}
my question is how object lock the block .
When a thread encounters a synchronized block (which uses objects for synchronization, as in your example) the following happens:
the Java runtime checks if an other thread has already started executing the synchronized block (and is not finished yet) with the same "blocking" object instance
If yes: our thread must wait (it is blocked) until the other thread finishes. After the other thread releases the lock (and no other waiting thread acquires the lock before out thread), ours can enter the block
If no: our thread can immediately enter the synchronized block
The same instance is a very important part, consider the following example:
public void method() {
Object object = new Object();
synchronized (object) {
//do something
}
}
In this example synchronization will effectively never happen, threads will never block. Because each thread creates a new instance before encountering the block. They never use the same.

How does capturing and releasing of lock of an object works in java synchronization?

If a thread is executing a synchronized method, will it release the lock of that object before fully completing the execution of that method ? If yes, in what kind of case ?
If one thread(A) is executing synchronized method and at same time other thread(B) tries to access same synchronized method (or any other synchronized method in that object) it will go to BLOCKED state, but if the other thread(B) tries to access non-synchronized method will it get the execution before the first thread(A) completes the execution of the synchronized method ? Or it will get the execution only after the first thread(A) completes the execution of synchronized method ?
A synchronized method is just a shortcut way of writing a synchronized block (see https://stackoverflow.com/a/26676499/801894). So, no matter whether you are talking about a synchronized instance method, or a synchronized static method or a synchronized block, you really are talking about the same thing in all three cases.
Java will never allow more than one thread to be synchronized on the same object at the same time. The only tricky part of understanding that rule is to know that if a thread calls foo.wait() from inside a synchronized(foo){...} block, then the thread will not be synchronized for some interval of time while it is inside the foo.wait() call. But, it is guaranteed that the thread will synchronize on foo again before the foo.wait() call returns.
The only other way a thread can give up its synchronization of foo is to leave the synchronized(foo) {...} block altogether.

Thread Safe Synchronization Block

I have some confusion regarding thread Synchronization. Consider i have two thread Thread1 and Thread2 and two method synchronized foo1() and foo2(). foo1() is synchronized method and foo2() is not, in foo1 internally there is a statement which calls foo2() and if Thread1 calls foo1() and in that it is working in foo2() method, at the same time Thread2 want to access foo2() method directly which is not synchronized.
So my question is
will Thread2 get access of Foo2()? or it will wait for Thread1 to complete its task?
If foo2() is not synchronized, any thread can call it any time without being blocked. It doesn't make any difference whether a thread is calling it from another method which is itself synchronized.
It is the object, not the method which is locked. This means you can have the two threads in foo1() if they are accessing different objects. If they are accessing the same object, the same lock will prevent concurrent access regardless of what is called first or what calls it.
BTW: foo1() can call itself as it already has the lock.
Thread2 won't be blocked and won't wait.
It will start execution Foo2, since it's not synchronized.
Thread2 can call foo2() directly,because foo2() not a synchronized method,so any thread can call it and not acquire the current object's monitor。

Does a synchronized objects handle pass to a called function in Java?

So lets say I have this code:
public void bar(){
synchronized(foo){foo.remove(0)}
}
public void doStuff(){
synchronized(foo){
bar()
}
}
Will synchronized realize that the current chain I'm in has this lock and inherit it or will it deadlock?
The lock you get from a synchronized block is reentrant. This will not dead-lock, a thread can acquire a lock on the same object multiple times.
See Intrinsic Locks and Synchronization.
As Mat said it won't dead lock.
How i see it as
that this lock mechanism isn't dependent over method call but
on control flow.
How a single thread is executing statements and when a thread
encounters a synchronized block then it ask for the lock of the object in the synchronized signature.
If it has it then it enters else will wait in the lock pool of the object until gets notified.
thread which executed doStuff() already carried the lock so thats why no case of deadlock

Do two synchronized methods execute simultaneously

I have 4 methods (m1, m2, m3 and m4) in a class. Method m1, m2 and m3 are synchronized methods. Also, I have 4 threads t1, t2, t3 and t4 respectively.
If t1 access the m1 method (synchronized method), could t2 thread access m2 method (synchronized method) simultaneously? If not what would be the state of t2?
If t1 access the m1 method (synchronized method), could t2 thread access m2 method (synchronized method) simultaneously?
The synchronized keyword applies on object level, and only one thread can hold the lock of the object. So as long as you're talking about the same object, then no, t2 will wait for t1 to release the lock acquired when it entered m1.
The thread can however release the lock without returning from the method, by calling Object.wait().
If not, what would be the state of t2 ?
It would sit tight and wait for t1 to release the lock (return from the method or invoke Object.wait()). Specifically, it will be in a BLOCKED state.
Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait.
Sample code:
public class Test {
public synchronized void m1() {
try { Thread.sleep(2000); }
catch (InterruptedException ie) {}
}
public synchronized void m2() {
try { Thread.sleep(2000); }
catch (InterruptedException ie) {}
}
public static void main(String[] args) throws InterruptedException {
final Test t = new Test();
Thread t1 = new Thread() { public void run() { t.m1(); } };
Thread t2 = new Thread() { public void run() { t.m2(); } };
t1.start();
Thread.sleep(500);
t2.start();
Thread.sleep(500);
System.out.println(t2.getState());
}
}
Output:
BLOCKED
If the methods are synchronized on the same monitor, then they cannot execute simultaneously in different threads. When the second thread comes to the monitor entry (the start of the synchronized method in this case), it will block until the first thread releases the monitor.
The actual state of the blocked thread in this case, as reported by jconsole, will be something like java.lang.Thread.State: WAITING (on object monitor)
Assuming all methods are normal instance methods, then they will share the same monitor when invoked on the same object. That is, if you had something like:
// Thread 1
A a1 = new A();
a1.m1();
// Thread 2
A a2 = new A();
a2.m2()
then in this case, the second thread will be able to call the method, because it's trying to obtain the implicit monitor of the a2 object, which is not locked by thread 1. But if thread 2 tried to call a1.m2(), then it would block until thread 1 had finished executing m1().
If you have static methods, then they obtain the explicit monitor of the class itself (A.class in my hypothetical-naming case), so will not be blocked by any instance method invocations.
No, it couldn't. That's the only point there is to synchronized: different threads can't do these things simultaneously (You don't have to guard against the same thread doing them simultaneously, because a single thread can't do anything in parallel at all.) The state of the waiting thread is 'waiting for lock'. (With a sufficiently modern JVM you can actually have this state displayed on the console if you ask in the right way.)
If t1 access the m1 method (synchronized method), could t2 thread access m2 method (synchronized method) simultaneously?
No. Thread t2 will wait for Thread t1 to release the lock.
In your same example, t2 can access method m4 which is not synchronized.
Locks In synchronized Methods
Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception
Coming back to your second query:
If not, what would be the state of t2 ?
Thread t2 is in blocked state and waiting for Thread t1 to release the lock.
From java documentation page:
making synchronized method have two effects.
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all thread

Categories

Resources