Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Java arrays in a static method thread safe?

   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!

like image 608
user247866 Avatar asked Nov 04 '11 21:11

user247866


People also ask

Are arrays in Java thread safe?

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.

Is Java static method 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.

Are arrays in Java static?

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.

How do I know if a method is thread safe?

A method will be thread safe if it uses the synchronized keyword in its declaration.


1 Answers

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.

like image 195
Dean Povey Avatar answered Oct 13 '22 11:10

Dean Povey