Search code examples
javathread-synchronizationjava-collections-api

Synchronizing on an object in Java


I am looking for something akin to this syntax even though it doesn't exist.

I want to have a method act on a collection, and for the lifetime of the method, ensure that the collection isn't messed with.

So that could look like:

private void synchronized(collectionX) doSomethingWithCollectionX() {
    // do something with collection x here, method acquires and releases lock on
    // collectionX automatically before and after the method is called
}

but instead, I am afraid the only way to do this would be:

private void doSomethingWithTheCollectionX(List<?> collectionX) {
    synchronized(collectionX) {
        // do something with collection x here
    }
}

Is that the best way to do it?


Solution

  • Yes it is the only way.

    private synchronized myMethod() {
        // do work
    }
    

    is equivalent to:

    private myMethod() {
        synchronized(this) {
             // do work
        }
    }
    

    So if you want to synchronize on an other instance than this, you have no other choice but declaring the synchronized block inside the method.