public static int rank(int key, int[] a) {
int lo = 0;
int hi = a.length - 1;
while (lo <= hi) {
// Key is in a[lo..hi] or not present.
int mid = lo + (hi - lo) / 2;
if (key < a[mid]) hi = mid - 1;
else if (key > a[mid]) lo = mid + 1;
else return mid;
}
return -1;
}
The above static method does binary search. Is it thread safe? I know that local variables are thread safe but “a” here is an array, so that means it’s an object in Java, right? Is that a problem?
The array is just being read, not modified in any way, so I’m assuming this method is thread-safe. But I want to make sure I understand why.
Thanks!
No arrays are not generally threadsafe. Whether your code is in this case depends on whether other threads have access to the array you passed in. Because arrays are passed by reference, then other threads can have access to them.
If you only create/modify the array in a single thread, or if you pass in a copy that is copied in a threadsafe way it will be fine.