Monitor and Synchronized keyword in Java - java

So I'm having problems understanding the distinction between a Java Monitor and the synchronized keyword.
I read that in Java, every class is basically a monitor. What is the purpose of declaring it as
monitor BankAccount{
double balance;
public void withdraw(){}
public void deposit(){}
}
Will every method of this class be synchronized or do I need to specify the keyword?

A monitor may be associated with every object instance in Java. This includes Class objects. There is, however, no keyword monitor. The monitor is synchronized upon when methods are invoked on an object that are declared synchronized or when an explicit synchronized block is used. Static methods synchronize on the monitor associated with the Class object representing the class type.

monitor isn't a keyword. Nothing is synchronized by default. You need the synchronized keyword on a method for it to be synchronized (or to use some other locking mechanism explicitly, but it won't happen automatically).

Related

What happens when a thread tries to call both static and non-static synchronized methods?

I have a class as
public class ThreadExample extends Thread{
static int count = 0;
public static synchronized int increment(){
return count++;
}
public synchronized int decrement(){
return count--;
}
}
Here I have one static method and one non-static method.
First thread1 have called method increment() which is synchronized.It acquires lock on class level.
Here my question is if another thread2 is calling decrement() method will that thread2 will acquire lock on decrement() and how it works?
The synchronized keyword has two possible uses. It can be used as a modifier for methods, and it can be used as a statement. Besides, the synchronized modifier can be combined with static, and in that case the target object will be the enclosing class instead of the enclosing instance.
Scope | modifiers | corresponding statement
---------+---------------------+------------------------
static | synchronized static | synchronized (X.class)
instance | synchronized | synchronized (this)
If a method is static synchronized, the lock is acquired on the class object of the enclosing class, in your case on ThreadExample.class.
Although they're compiled into different byte code, the following two methods are equivalent:
public class Foo {
// static method with synchronized modifer
public static synchronized void foo1() {
// ...
}
// equivalent synchronized statement
public static void foo2() {
synchronized (Foo.class) {
// ...
}
}
}
If a method is synchronized (without static), the lock is acquired on the instance itself. Although they're compiled into different byte code, the following two methods are equivalent:
public class Foo {
// instance method with synchronized modifier
public synchronized void foo3() {
// ...
}
// equivalent synchronized statement
public void foo4() {
synchronized (this) {
// ...
}
}
}
So, increment() and decrement() are synchronized differently, and there can be a race condition.
Therefore, the variable count is not sufficiently protected from concurrent update.
++ and -- cannot be atomic themselves, as incrementing or decrementing a value requires a read-update-write cycle. Technically it could be atomic because some CPUs provide atomicity for that by providing corresponding instructions which will keep the bus / address obtained for themselves until the operation is performed. But the JVM does not rely on such things.
If you need a atomic int, you might want to look at java.util.concurrent.atomic.AtomicInteger.
How to do synchronized in C
synchronized is implemented with the VM environment methods MonitorEnter() and MonitorExit().
Pitfalls
When you use the synchronized modifier, you synchronize on something which is more or less public, i.e. visible to other objects and classes as well. The Monitor feature of java.lang.Object which provides the underlying facility for synchronized is public, as well as the native functions MonitorEnter() / MonitorExit() and the wait pool methods wait(), notify() and notifyAll(). This can lead to unexpected bugs and deadlocks if "somebody else" is also using "your object / your class" for synchronization.
Therefore it has become a pattern to actually not use the synchronized modifier but instead use synchronized statements on a private lock object, like this:
public class Foo {
private final Object lock = new Object();
public void foo() {
synchronized (lock) {
// ...
}
}
}
Now Foo can no longer be disturbed or blocked by somebody else synchronizing on it. You might think there might be a reasonable use case for that, but I think if you have a use case for locking across object / class boundaries, there's probably a big flaw in the design - things are not self-contained enough.
If you need a class lock instead of an instance lock, just make the variable static.
Note that when doing serialization, you will have to take care of the lock object. The simplest way is to actually not use Object, but this:
public class Lock implements Serializable {}
If you want to save serialization storage, you can declare the lock transient and recreate the lock during deserialization, but be careful about transient final, you need reflection or readResolve() for them, but that's a different story.
Calling synchronized static methods tries to acquire the lock of the class object. (ThreadExample in your case), while calling synchronized non-static methods tries to acquire the lock of the particular instance object. So essentially you are acquiring 2 different locks and thus your code is not thread-safe. The data count may be corrupted due to race condition
Oracle tutorial:
You might wonder what happens when a static synchronized method is
invoked, since a static method is associated with a class, not an
object. In this case, the thread acquires the intrinsic lock for the
Class object associated with the class. Thus access to class's static
fields is controlled by a lock that's distinct from the lock for any
instance of the class.
Static and instace level locks are two different locks and they are independant of each other.
Regarding scenario in question "First thread1 have called method increment() which is synchronized.It acquires lock on class level. Here my question is if another thread2 is calling decrement() method will that thread2 will acquire lock on decrement() and how it works"
even if thread1 is holding (class level)lock on increment method and thread2 calls decrement method it should aquire a (instance level)lock .
problem is not with aquiring the lock problem might start when they are trying to updated the shared variable.If two threads are trying to access count variable (one through static locking and other through instance level locking ) at a same time then there might be a RACE condition between two threads.
As suggested by Christian you can overcome this by using java.util.concurrent.atomic.AtomicInteger instead of int
For more details please visit URL
A static synchronized method and a non-static synchronized method will not block each other. The reason is static method locks on a Class instance while the non-static method locks on the this instance— both actions do not interfere with each other at all.
In your code one method is static synchronized and another method is just synchronized. Your code is not thread safe, even if two threads are executing two methods on same object, one thread (executing non-static method) acquires object level lock and proceed. Another thread executing static method acquires class level lock (i.e. ThreadExample.class ) and proceeds. Remember that static methods are always class level.
To make your code thread safe you need to have below changes in your example.
public static synchronized int decrement(){
return count--;
}

Thread safety for static variables in java

My question is related to thread safety of static variables.
Class A{
private static int test=0;
public static void synchronized m1(){
test=test+1;
}
public void synchronized m2(){
test=test+1;
}
}
If two threads, t1 having static lock and t2 having object lock, can
continue simultaneously, then how will state test of class A will be
thread safe?
May be , I am missing something very basic, but not sure how it works.
Based on below answers, I get the impression that if such states have
to be made thread safe, then either both locks should be held by a
thread which is updating this state, or make sure it is being accessed
by either only static methods or only non-static methods. right?
This is not thread safe. The methods use different monitor objects: the static method uses the class, and the instance method synchronizes using the object instance. You can make the instance method use the class as the monitor object by:
synchronized (A.class) {
...
if you need to. I'd consider making both methods static though, unless you need to access instance variables.
Its not thread-safe, and you (the question author) explained very well why.

What is the use of static synchronized method in java?

I have one question in my mind. I have read that static synchronized method locks in the class object
and synchronized method locks the current instance of an object. So what's the meaning of locked
on class object?
Can anyone please help me on this topic?
In general, synchronized methods are used to protect access to resources that are accessed concurrently. When a resource that is being accessed concurrently belongs to each instance of your class, you use a synchronized instance method; when the resource belongs to all instances (i.e. when it is in a static variable) then you use a synchronized static method to access it.
For example, you could make a static factory method that keeps a "registry" of all objects that it has produced. A natural place for such registry would be a static collection. If your factory is used from multiple threads, you need to make the factory method synchronized (or have a synchronized block inside the method) to protect access to the shared static collection.
Note that using synchronized without a specific lock object is generally not the safest choice when you are building a library to be used in code written by others. This is because malicious code could synchronize on your object or a class to block your own methods from executing. To protect your code against this, create a private "lock" object, instance or static, and synchronize on that object instead.
At run time every loaded class has an instance of a Class object. That is the object that is used as the shared lock object by static synchronized methods. (Any synchronized method or block has to lock on some shared object.)
You can also synchronize on this object manually if wanted (whether in a static method or not). These three methods behave the same, allowing only one thread at a time into the inner block:
class Foo {
static synchronized void methodA() {
// ...
}
static void methodB() {
synchronized (Foo.class) {
// ...
}
}
static void methodC() {
Object lock = Foo.class;
synchronized (lock) {
// ...
}
}
}
The intended purpose of static synchronized methods is when you want to allow only one thread at a time to use some mutable state stored in static variables of a class.
Nowadays, Java has more powerful concurrency features, in java.util.concurrent and its subpackages, but the core Java 1.0 constructs such as synchronized methods are still valid and usable.
In simple words a static synchronized method will lock the class instead of the object, and it will lock the class because the keyword static means: "class instead of instance".
The keyword synchronized means that only one thread can access the method at a time.
And static synchronized mean:
Only one thread can access the class at one time.
Suppose there are multiple static synchronized methods (m1, m2, m3, m4) in a class, and suppose one thread is accessing m1, then no other thread at the same time can access any other static synchronized methods.
static methods can be synchronized. But you have one lock per class. when the java class is loaded coresponding java.lang.class class object is there. That object's lock is needed for.static synchronized methods.
So when you have a static field which should be restricted to be accessed by multiple threads at once you can set those fields private and create public static synchronized setters or getters to access those fields.
Java VM contains a single class object per class. Each class may have some shared variables called static variables. If the critical section of the code plays with these variables in a concurrent environment, then we need to make that particular section as synchronized. When there is more than one static synchronized method only one of them will be executed at a time without preemption. That's what lock on class object does.

What is the difference between synchronized(this) and synchronized(ClassName.class)?

I read somewhere that synchronized(this) should be avoided for various reasons. Yet some respectable code that I encountered uses the following in the constructor:
public SomeClass(Context context) {
if (double_checked_lock == null) {
synchronized (SomeClass.class) {
if (double_checked_lock == null) {
// some code here
}
}
}
}
Is there really a difference between synchronized(this) and synchronized(SomeClass.class)?
synchronized(this) is synchronized on the current object, so only one thread can access each instance, but different threads can access different instances. E.g. you can have one instance per thread.
This is typically useful to prevent multiple threads from updating an object at the same time, which could create inconsistent state.
synchronized(SomeClass.class) is synchronized on the class of the current object ( or another class if one wished) so only one thread at a time can access any instances of that class.
This might be used to protect data that is shared across all instances of a class (an instance cache, or a counter of the total number of instances, perhaps) from getting into an inconsistent state .
this is different for each instance.
ClassName.class is not.
Therefore, synchronized(this) will allow multiple instance to run simultaneously.
The synchronized keyword, when applied to a class locks on the class, and when it's applied to this locks on the current object instance. From the Java Language Specification, section 8.4.3.6, 'synchronized Methods':
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.
Each java Object can have a lock. This lock can be held by at most one thread at a time, any other thread has to wait to get the lock of the same object.
synchronized(this) acquires the lock of the instance this for the current thread. The method can run parallel on different instances (different values for this and therefore different locks)
synchronized(SomeClass.class) acquires the lock of the global class object of SomeClass. Only one instance of the method can run as all object instances lock on the same global object (same lock).
These are 2 different object to lock on:
'this' refer to current instance context, so creating multiple instances will have no effect if, for example, each thread using a different instance and lock on it. 'this' can be referred only on non-static context.
the 'class' is a static member of the Java Class and there is exactly one instance of it. You can lock on it in both static and non-static context.
synchronized(this) synchronizes on the instance of the object.
synchronized(SomeClass.class)uses the instance of the Class object that represents SomeClass, which is global for all instances in the same classloader.
Thus, these are different constructs with different semantics.
Using synchronized alone, or as a method modifier, also synchronizes on the instance's semaphore, which is normally used to prevent contention between multiple threads accessing that instance as a shared resource (i.e. a List).
The thread you refer states that it's a better practice to use a private instance, as synchronizing directly on your object instance may be dangerous. For that you'd use:
class MySharedResourceClass {
private SomeClass lock = new SomeClass();
public doSomething() {
synchronized (lock) {
// Do something here
}
}
}

Java: A synchronized method in the superclass acquires the same lock as one in the subclass, right?

class A {
public synchronized void myOneMethod() {
// ...
}
}
class B extends A {
public synchronized void myOtherMethod() {
// ...
}
}
// ...
B myObject;
// ...
myObject.myOneMethod(); // acquires lock
myObject.myOtherMethod(); // same lock?
How I understand the synchronization model, I'd say that yes, it does, because the lock / monitor is associated with the instance myObject, and it doesn't matter where the method was defined. But am I right? If not, why? If yes, why are you sure, and I'm not? :-)
Yes, you are right, and you got the explanation right too. Nothing much to add.
Note that if the methods were static, then they would synchronize on different objects, namely their respective classes (A and B).
EDIT: Why am I sure? I don't know, why are you not sure? ;-) myObject is just one object - there isn't any distinction between the myObject attributes that come from class A and those that come from class B. (Well, technically you could probably use reflection to find out which are which, so there must be some distinction, but forget about reflection for now. For common operations on the object there's no distinction.)
Yes, synchronized is equivalent to synchronized(this).
To be more precise:
For a class (static) method, the lock associated with the Class object for the method's class is used. For an instance method, the lock associated with this (the object for which the method was invoked) is used.
If you want to be more explicit about your locking, you could do something like this:
class A {
protected final Object mutex = new Object();
public void myOneMethod() {
synchronized (mutex) {
// ...
}
}
}
class B extends A {
public void myOtherMethod() {
synchronized (mutex) {
// ...
}
}
}
In fact, this pattern is recommended by Brian Goetz in Java Concurrency in Practice, section 4.2.1 "The Java monitor pattern". That way you know exactly where your monitor is coming from.
Yes. Java uses "monitors" to implement synchronization, and synchronized methods use the object instance they're called on as monitor, which is obviously the same in this case.
Note that this is NOT true for static methods! There, the class instance of (I think) the declaring class is used, which would not be the same one.
Yes you are correct
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. In this case the object is B
Just a small addition for people who might be interested in the future..
Additionally remember that locks in Java are reentrant. If they were not this code of yours would result in a deadlock since as you've indicated both operations require the same lock.
From the conceptual viewpoint, the mutex integrity of some inheritance scenarios would be broken if synchonized methods of class A would only protect A's data in the context of subclass B. After all, not all of A's data is required to be private.
Imagine that you want to slightly extend the functionality of one method of A while keeping the rest of A's functionality including mutex protection. If A were only protecting itself, you would end up having to override all of A's synchronized methods to lift the original synchronization mechanism to the new subclass. Not very attractive and also not very efficient.

Categories

Resources