When to synchronize a variable?
When should I synchronize a variable ?
I think it wil开发者_运维百科l just be accessed by one thread; does this mean I don't need to synchronize it?
synchronized(variableName){
}
If it will only be accessed by one thread, you don't need to synchronize it.
You should synchronize in a multithread environment when you want to protect a variable from simultaneous update from multiple threads.
As per your code snippet, you are synchronizing on variableName
and you are not synchronizing variableName
. There is a lot of difference between this. If you want to protect the variableName
then that should be accessed in the synchronized
block. Like this:
synchronized(syncVar){
variableName = /* some operation which will modify the state of variableName */
}
Here syncVar
is the variable on which you are synchronizing and protecting variableName
from simultaneous access.
Also, if there is just one thread to access that variable, no need to synchronize. It can be a performance hit.
The reason for sychronization is when a block of code may be accessed by multiple threads. Using the following,
synchronized(whateverObject)
{ //...
// code to be accessed by one thread here...
}
ensures that the code block will be accessed by only one thread. All other threads will block until the first thread is finished with it.
There is no need to use the synchronized keyword unless the code is multithreaded.
If performance is a high consideration, I recently read:
void synchronized method() {
...
}
is faster than:
void method() {
synchronized (this) {
...
}
}
in current JVMs. YMMV
精彩评论