I have some questions regarding the usage and significance of the synchronized
keyword.
- What is the significance of the
synchronized
keyword? - When should methods be
synchronized
? - What does it mean programmatically and logically?
I have some questions regarding the usage and significance of the synchronized
keyword.
synchronized
keyword?synchronized
?
The
synchronized
keyword is all about different threads reading and writing to the same variables, objects and resources. This is not a trivial topic in Java, but here is a quote from Sun:In a very, very small nutshell: When you have two threads that are reading and writing to the same 'resource', say a variable named
foo
, you need to ensure that these threads access the variable in an atomic way. Without thesynchronized
keyword, your thread 1 may not see the change thread 2 made tofoo
, or worse, it may only be half changed. This would not be what you logically expect.Again, this is a non-trivial topic in Java. To learn more, explore topics here on SO and the Interwebs about:
Keep exploring these topics until the name "Brian Goetz" becomes permanently associated with the term "concurrency" in your brain.
synchronized
means that in a multi threaded environment, an object havingsynchronized
method(s)/block(s) does not let two threads to access thesynchronized
method(s)/block(s) of code at the same time. This means that one thread can't read while another thread updates it.The second thread will instead wait until the first thread completes its execution. The overhead is speed, but the advantage is guaranteed consistency of data.
If your application is single threaded though,
synchronized
blocks does not provide benefits.Well, I think we had enough of theoretical explanations, so consider this code
Note:
synchronized
blocks the next thread's call to method test() as long as the previous thread's execution is not finished. Threads can access this method one at a time. Withoutsynchronized
all threads can access this method simultaneously.When a thread calls the synchronized method 'test' of the object (here object is an instance of 'TheDemo' class) it acquires the lock of that object, any new thread cannot call ANY synchronized method of the same object as long as previous thread which had acquired the lock does not release the lock.
Similar thing happens when any static synchronized method of the class is called. The thread acquires the lock associated with the class(in this case any non static synchronized method of an instance of that class can be called by any thread because that object level lock is still available). Any other thread will not be able to call any static synchronized method of the class as long as the class level lock is not released by the thread which currently holds the lock.
Output with synchronised
Output without synchronized