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!
Arrays are 'value-typed' in the effect of assignment, initialization, and argument passing — creates an independent instance with its own unique copy of its data. Immutable arrays (declared using let) are thread-safe since it is read-only. But mutable arrays are not thread-safe.
A data type or static method is threadsafe if it behaves correctly when used from multiple threads, regardless of how those threads are executed, and without demanding additional coordination from the calling code.
Java array can also be used as a static field, a local variable, or a method parameter. The size of an array must be specified by int or short value and not long. The direct superclass of an array type is Object.
A method will be thread safe if it uses the synchronized keyword in its declaration.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With