简体   繁体   中英

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
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM