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?
3 Answers
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.
3 Comments
synchronized keyword in Java allows a thread to enter what is called a Monitor, which is alot like a Semaphore. I don't recall from school what the differences were, except that Semaphores are used in C, and Monitors require Object-Oriented langauges like C++ and Java.synchronized keyword really reminds me of a Mutex lock, rather than a Semaphore because it seems that only one thread can enter the "Critical Region" at a single time, while the other threads have to wait for it. You can't specify the number of threads allowed to enter a monitor in Java?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.
Comments
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.