Are Java arrays in a static method thread safe?

2019-04-06 17:11发布

   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!

3条回答
ら.Afraid
2楼-- · 2019-04-06 17:15

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.

查看更多
走好不送
3楼-- · 2019-04-06 17:20

The method itself is thread-safe, since it only takes its arguments and reads them, without publishing them to any other thread. But that doesn't mean you couldn't have a threading problem. It all depends on where the arguments come from.

If the arguments constitute shared state between threads, then every access to this state should be synchronized somehow. But you have to establish a synchronization policy between threads to protect the access to this state. So this method, or the caller of this method, should make sure the access to the state is thread-safe. Without knowing where the arguments come from, it's thus impossible to tell if this code is thread-safe or not.

查看更多
可以哭但决不认输i
4楼-- · 2019-04-06 17:34

yes, it is thread safe, as you say you only read the array, the only possible trouble can be if an another thread is updating the array the same time as this method reads it

查看更多
登录 后发表回答