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 sortA
and passing a reference to the same array, you'd be in trouble without synchronized
, because they would interfere with eachother.
Beware, that it would seem from the example that the getList
method returns a new List
from an array, such that even if the threads pass the same array, you get different List
objects. This is misleading. For example, using Arrays.asList
creates a List
backed by the given array, but the javadoc clearly states that Changes to the returned list "write through" to the array.
so be careful about this.