I have started learning concurrency and threads in Java. I know the basics of synchronized (i.e. what it does). Conceptually I understand that it provides mutually exclusive access to a shared resource with multiple threads in Java. But when faced with an example like the one below I am confused about whether it is a good idea to have it synchronized. I know that critical sections of the code should be synchronized and this keyword should not be overused or it effects the performance.
public static synchronized List<AClass> sortA(AClass[] aArray)
{
List<AClass> aObj = getList(aArray);
Collections.sort(aObj, new AComparator());
return aObj;
}
public static synchronized List<AClass> getList(AClass[] anArray)
{
//It converts an array to a list and returns
}
Assuming each thread passes a different array then no synchronization is needed, because the rest of the variables are local.
If instead you fire off a few threads all calling
sortAand passing a reference to the same array, you’d be in trouble withoutsynchronized, because they would interfere with eachother.Beware, that it would seem from the example that the
getListmethod returns a newListfrom an array, such that even if the threads pass the same array, you get differentListobjects. This is misleading. For example, usingArrays.asListcreates aListbacked by the given array, but the javadoc clearly states thatChanges to the returned list "write through" to the array.so be careful about this.