user919860
user919860

Reputation: 3175

Synchronized Methods in Java

Just wanted to check to make sure that I understand this. A synchronized method doesn't create a thread, right? It only makes sure that no other thread is invoking this method while one thread within the same process (ie the JVM) is using it, right?

Upvotes: 12

Views: 11517

Answers (3)

mre
mre

Reputation: 44250

A synchronized method doesn't create a thread, right?

Right.

It only makes sure that no other thread is invoking this method while one thread within the same process (ie the JVM) is using it, right?

Right.

For more information, read Synchronized Methods. I also recommend reading Java Concurrency in Practice.

Upvotes: 21

toto2
toto2

Reputation: 5326

Yes.

There is another important role for synchronized blocks too: when a thread enters a synchronized block it sees the changes to the values made by the previous thread that accessed that block (or another block synchronized with the same lock).

Basically on a multicore cpu, each thread as its own memory cache on its core: each core has copies of the same variables, their values might be different on each core. When there is a synchronized operation, the JVM makes sure that the variable values are copied from one memory cache to the other. A thread entering a synchronzed block then sees the values "updated" by a previous thread.

As suggested by mre, Java Concurrency in Practice is a good reference if you really want to understand multithreading and learn best practices.

Upvotes: 3

Jon7
Jon7

Reputation: 7225

That's mostly correct. Calling a synchronized method does not spawn a new thread. It just makes other threads block when they try to call any other synchronized method for that instance of that object.

The key thing to remember is that all synchronized methods of a class use the same lock.

Upvotes: 3

Related Questions