What is this:
synchronized (this) {
// ...some code...
}
good for? (Could you write an example?)
What is this:
synchronized (this) {
// ...some code...
}
good for? (Could you write an example?)
It prevents concurrent access to a resource. Sun's got a pretty good description with examples.
It prevents multiple threads from running the code contained within the braces. Whilst one thread is running that code, the remainder are blocked. When the first thread completes, one of the blocked threads will then run the synchronised code, and so on.
Why do you want to do this ? The code within the block may modify objects such that they're in an inconsistent state until the blocks exits. So a second thread coming in would find inconsistent objects. From that point on chaos ensues.
An example would be removing an object from one pool and inserting it in another. A second thread might run whilst the first thread is moving the object, and subsequently find the object referenced in both collections, or neither.
You can also use this mechanism to restrict multiple threads from accessing a resource designed to be used by one resource (e.g. a trivial database, for example).
Synchronizing threads has the effect of serializing access to blocks of code running on the thread. Serializing in this context means giving one thread at a time the right to execute specific block of code.
Note that the following two are equivalent:
synchronized void someMethod() {
// ...
}
and
void someMethod() {
synchronized (this) {
// ...
}
}