netik
netik

Reputation: 1826

Monitor and Synchronized keyword in 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?

Upvotes: 1

Views: 1131

Answers (2)

Thomas B Preusser
Thomas B Preusser

Reputation: 1189

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.

Upvotes: 3

Louis Wasserman
Louis Wasserman

Reputation: 198133

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).

Upvotes: 2

Related Questions