w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Java Synchronized Collections vs Object

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




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.