操纵不同的阵列(对象数组)索引时需要同步 [英] Is synchronization needed when manipulating different array(object array) indices

查看:127
本文介绍了操纵不同的阵列(对象数组)索引时需要同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行Java的背景下,我有一个code这样的,

In the context if Java, I have a code like this,

MyObject[] array;

和在不同的线程我有一个code这样的

and in different threads i have a code like this

array[i] = new MyObject(val);

如果我保证我的每个线程使用的 I ,那么我会需要同步上述声明采取的竞争条件照顾不同的价值观?

If I ensure that each of my threads use different values of "i" then would I need to synchronize the above statement to take care of race conditions?

推荐答案

也许吧。如果每个任务数组中写到不同的位置,他们就不会互相覆盖的输出。这样的作品。

Maybe. If every task wrote to a different location in the array, they wouldn't overwrite each other's output. So that works.

您可能面临的一个问题,当最后处理数组,不过,因为Java不作保证,当值写入到存储器中。优化器可以决定写真正晚期(或已经太晚了)的值。因此,应使数组挥发性这意味着没有缓存必须发生在其访问时的值

You might face an issue when finally processing the array, though, since Java doesn't make guarantees when the values are written to memory. The optimizer could decide to write the values really late (or too late for you). Therefore, you should make the array volatile which means that no caching must happen when accessing the values in it.

这篇关于操纵不同的阵列(对象数组)索引时需要同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆