Java Synchronization [closed]

What is this:

synchronized (this) {
    // ...some code...
}

good for? (Could you write an example?)


Solution 1:

It prevents concurrent access to a resource. Sun's got a pretty good description with examples.

Solution 2:

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).

Solution 3:

Note that the following two are equivalent:

synchronized void someMethod() {
    // ...
}

and

void someMethod() {
    synchronized (this) {
        // ...
    }
}