user2686811
user2686811

Reputation: 629

Java Synchronized Collections vs Object

I'm wondering what the difference is between these ways of synchronization

List<Integer> intList = Collections.synchronizedList(new ArrayList<Integer>());

synchronized (intList) {
    //Stuff
}

and using an object lock

Object objectLock = new Object();

List<Integer> intList = new ArrayList<Integer>();

synchronized (objectLock) {
    //Stuff
}

Upvotes: 2

Views: 146

Answers (2)

Francisco Meza
Francisco Meza

Reputation: 883

The code you show is not necessarily thread safe yet!!

The only difference between one excerpt and the other is the object you use as a monitor for synchronization. This difference will determine which object should be used for synchronization by other threads that need access to the mutable data you're trying to protect

great read for this: java concurrency in practice

Upvotes: 0

user2357112
user2357112

Reputation: 280708

The first approach makes sure that individual method calls are synchronized, and it avoids needing to manage a separate lock object. One thread can call

intList.add(3);

and another can call

intList.clear();

without a synchronized block, and it'll be properly synchronized. (Unfortunately, this doesn't help when you need to hold the lock for a group of function calls; then, you need a synchronized block around those calls.) Also, if you need to pass the list around, you can use

otherObject.doStuffWith(intList);

and

return intList;

instead of

otherObject.doStuffWith(intList, objectLock);

and

return ListAndLock(intList, objectLock);

Upvotes: 6

Related Questions