synchronized methods can execute simultaneously? - java

I have created 2 objects and 2 threads.
Assume m1() and m2() are synchronized methods.
t1.m1();
t2.m2();
can both threads can execute simultaneously ? is it possible both synchronized methods can execute simultaneously?

Synchronization happens on specific instances. Synchronized methods synchronize on the instances the method is called on. Thus, t1.m1() and t2.m2() can execute simultaneously if and only if t1 and t2 refer to different instances.

Yes, if both are non-static and are executed using two different instances.
Explanation added.
Because monitor is actually associated with the instance. So, if one thread acquired the lock on one instance, the thread is free to invoke the method on the other instance.

They can execute simultaneously, since synchronized methods lock on the instance.
synchronized void someMethod(){
}
is the same as
void someMethod(){
synchronized(this){
}
}
So every instance has its own lock to synchronise on.
Static methods use the class instance instead (SomeClass.class).

Yes, if they are instance methods of different instances, they are synchronization does not happen.

Synchronization is always done on a monitor. Only one thread can access a monitor at a time.
When you are synchronizating methods, the monitor is either the object (non-static) or the Class-object (static methods).
You should think of
public synchronized void myMethod(){
...
}
as:
public void myMethod(){
synchronized (this) {
...
}
}
Since you are having two independent object instances with a synchronized method, you have 2 different monitors.
Result: Both Threads can work simultaneously.

Related

Single instance, synchronized and non synchronized methods accessing by multiple threads

Here my question is: I have a class with 2 methods one is non static synchronized and another is non static non synchronized method. Now 2 threads trying to access same instance of synchronized and non synchronized methods at a time. What will happen if thread one access non static synchronized method first? Can it be possible second thread to access non static non synchronized method of same instance when first thread apply lock on same instance?
Thanks Chandra
Yes the second thread can access the non synchronised method. There is no lock needed to access the method and can be done so by any thread. If the methods were both in the below format.
1. Static and synchronized. Will have to wait on the class level lock
2. Non static and synchronized. Will have to wait on object level lock

Is the process thread safe?

In my recent interview by explaining a situation they asked if the process is thread-safe
There are two synchronized methods one is static and other is not static i.e., non-static Method A and static Method B. These two methods access a shared data.
Now thread A calls non-static method A and thread B is calls static method B. Is this thread safe and explain y?
No, it's not thread-safe. For it to be thread-safe the different threads have to access the shared data using the same lock, but the two methods use different locks. Putting synchronized on a static method uses the class as a lock, putting synchronized on an instance method uses the object as a lock.
If the threads use different locks then neither thread is blocked, and both can access or modify the data concurrently. Even if the threads are only accessing data, and neither modifies it, locking would assure memory visibility. Without the shared lock you can't rely on that visibility. Unrestricted concurrent access would be safe only if the data is immutable and is already safely published.
Assuming the shared data has to be mutable, the fix would be for both methods to use the same lock. You can always specify your own lock if you use a synchronized block (rather than adding synchronized to the method), so the instance method could use:
public void yourInstanceMethod() {
synchronized(WhateverYourClassIs.class) {
// code accessing shared data
}
}

Java Threading Tutorial

I'm looking through the Java concurrency tutorials to get an idea of how this works in Java and had a question regarding the "MsLunch" example # http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html
I'm trying to understand in the MsLunch example, the difference between coding it as shown, and using 2 synchronized methods.
From what I can understand, using the synchronized keyword on methods relies on an instrinic lock associated with that methods object. So if a class has two synchronized methods a() and b(), a() and b() cannot be called concurrently on the same object.
But coding a() and b() as shown in the MsLunch class allows both methods to be called on the same object at the same time.
Is my understanding correct?
MsLunch example uses synchronized blocks with different object instances to lock. Hence both inc1() and inc2() can run concurrently.
If it were synchronized methods, in that case this will be used to lock, methods inc1() and inc2() would be executed serially.
In http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html
MSLunch is having Sync block rather than sync methods that too on two different locks so Yes Two threads will not be mutually blocked and will be able to access methods at the same time.

Java synchronized() keyword -- protection against changes of the object referenced in the field?

I know that
synchronized(objA) {
objA.readSomething();
}
protect object from being modified by another thread. But what if objA is declared as
class A {
public B objB;
public void readSoemthing() {
objB.readSomething();
}
}
and during the following block, another thead calls objB.modifySomething()? Suppose that thread somehow has its own reference to objB.
Will that be safe? if not, what's the proper way of handling it (i.e. I don't want any thread to modify anything inside A, even if it's a field that points to a different object, I don't want that object being modified).
synchronized(objA) {
objA.readSomething(); // at this point antoher thread calls objB.modifySomething()
}
The first part of your question is incorrect. The synchronized block only makes sure that no other thread can enter a block of code that is also synchronized on the object referenced by objA while the synchronized block is executing.
So any other thread might modify objA concurrently, unless all the methods that modify objA are synchronized.
Now that you know that, you also know that any other thread can get objB from objA and do whatever it wants with objB, unless all the methods of objB are also synchronized on objA.
This is why encapsulation is critical in thread-safe classes. All the methods accessing (read or write) shared state of an object should go through a synchronized method of that object. And the shared state should never be exposed to the outside.
That would not be thread safe. That's why you should "encapsulate" objB inside of objA by disallowing direct access to it (i.e. make it private).
I know that
synchronized(objA) {
objA.readSomething();
}
protect object from being modified by another thread. But what if objA
is declared as
This doesn't prevent objA from being modified by another thread, it ensures that another thread cannot obtain the monitor of objA while calling objA.readSomething() from the piece of code you posted.
You are not really protecting against modification with synchronized. All you are doing is preventing two threads from accessing that same method concurrently (or any other method or code block that uses the same object instance for synchronization). Synchronization is about concurrency (i.e. multi-threading) not write protection.
If you absolutely don't want modifications you should use the modifiers private or protected so that the respective write method is only accessed from the class(es) you want.
If on the other hand you want to avoid concurrent modifications, or avoid reading while writing (and vice-versa) you need to synchronize the read and write methods with the same object (in your case ObjA). It might also make sense to use the right modifiers to protect the methods from being accessed from classes you don't want.
Also remember that if a Thread has gained access to the synchronisation monitor of an object it can call all the methods that are synchronising on the same object.

Java Thread lock on static method

As per my knowledge in Java class with
Non static synchronize method : lock acquire on particular object
Static synchronize method : lock acquire on class
I am little bit confuse with this, since we can call the static method by class name OR by object name.
Please assume there are 4 methods is my class all are synchronized. 2 methods are static and 2 are not static. If I create 1 object of my class "obj1" and there are 2 threads Thread1 and Thread2 as well
Question 1: if I will try to access the static synchronized method, using the obj1 (or class name), does it mean there is no lock on "obj1", only 2 static methods will be locked (class level lock)? Does this mean another thread can access non-static method, but not the static method using the "obj1" simultaneously?
Question 2: if I will try to access the non-static synchronized method using the obj1 in Thread1, does it mean only 2 methods are locked for Thread2? Does this mean Thread2 can access 2 static methods, OR we can access the static method using the className(MyClass) as well simultaneously?
Question 3: if all the methods in my class are static and synchronized, does it mean there will be no object level lock and there is only one class level lock for all threads?
Please explain little bit about the class level lock.
Even if you call a static method with
someObject.staticMethod()
It doesn't change the fact that the lock is on the Class object. It just means that you're calling static methods in a confusing way and you should call it properly. Just because it works perfectly well, doesn't mean it should be used (unless you intend to make your code less readable).
There's nothing special about the class level lock. It just uses the Class object instead of the instance, and since all static synchronization uses the same Class object, it works like it does.
As for your last question, yes. If you have only static synchronized methods, they will all share the Class object as their lock, no matter how many instances of the class you have created.

Categories