线程安全-传递给线程的最终本地方法变量? [英] Thread Safe - final local method variable passed on to threads?

查看:85
本文介绍了线程安全-传递给线程的最终本地方法变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果此方法的变量'commonSet'改为类级别字段,则以下代码将引起相同的问题.如果这是一个类级别的字段,由于HashSet不是线程安全的,我将不得不在同步块中包装添加到set操作.我应该在以下代码中执行相同的操作,因为多个线程正在添加到集合中,或者甚至当前线程可能会继续对集合进行变异.

Will the following code cause same problems, if variable 'commonSet' of this method was instead a class level field. If it was a class level field, I'll have to wrap adding to set operation within a synchronized block as HashSet is not thread safe. Should I do the same in following code, since multiple threads are adding on to the set or even the current thread may go on to mutate the set.

public void threadCreatorFunction(final String[] args) {
    final Set<String> commonSet = new HashSet<String>();

    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            while (true) {
                commonSet.add(newValue());
            }
        }
    };

    new Thread(runnable, "T_A").start();
    new Thread(runnable, "T_B").start();
}

通过使用final来锁定"对"commonSet"的引用.但是,对其进行操作的多个线程仍可能破坏集合中的值(它可能包含重复项?).其次,混淆是因为'commonSet'是方法级别的变量-它的引用将位于调用方法(threadCreatorFunction)的堆栈存储器和运行方法的堆栈存储器中-这是正确的吗?

The reference to 'commonSet' is 'locked' by using final. But multiple threads operating on it can still corrupt the values in the set(it may contain duplicates?). Secondly, confusion is since 'commonSet' ia a method level variable - it's same reference will be on the stack memory of the calling method (threadCreatorFunction) and stack memory of run methods - is this correct?

与此相关的问题很多:

  • Why do variables passed to runnable need to be final?
  • Why are only final variables accessible in anonymous class?

但是,我看不到他们在这样的共享/传递可变项上强调线程安全部分.

But, I cannot see them stressing on thread safe part of such sharing/passing of mutables.

推荐答案

不,这绝对不是线程安全的.仅仅因为您在一个最终变量中添加了它,这意味着两个线程都将看到相同的 reference ,这很好-但它不会使 object 成为任何对象更加线程安全.

No, this is absolutely not thread-safe. Just because you've got it in a final variable, that means that both threads will see the same reference, which is fine - but it doesn't make the object any more thread-safe.

您需要同步访问权限,或者使用 ConcurrentSkipListSet .

Either you need to synchronize access, or use ConcurrentSkipListSet.

这篇关于线程安全-传递给线程的最终本地方法变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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