If I want to lock the whole array I can use the synchronized keyword like this:
int arr[];
synchronized void inc(int a, int b){
arr[a]=arr[a]+b;
}
But can I lock just the item arr[a] so that other threads can still read/write other items of the array at the same time?
Not out-of-the-box, but you can create an Object array that is the same size as your int array and populate the array with distinct Objects. So when you want to lock on a particular element in the int array, you lock on that Object at the corresponsible index:
When locking: do