有这两个java.io.File线程安全问题被回避? [英] Have these two java.io.File thread safety issues been evaded?

查看:658
本文介绍了有这两个java.io.File线程安全问题被回避?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 Win32FileSystem beginMultiThreading 在一个共享的MultiThreadingClass对象上多次同时运行,那么最可能的方式是什么这可能会导致数据竞争或其他线程问题?我知道这可能不是线程安全的,因为(1) setPath 的参数被重用。我还看到(2) path 不是 java.io.File 中的最终变量。但是,由于线程问题,我似乎无法找到代码可能自行错误的部分。

  public class MultiThreadingClass {
private Holder h = new Holder();
private String path =c:\\somepath;
public void beginMultiThreading(){
h.setPath(new File(path));
h.begin();
}
}

公共类持有者{
私有文件路径;
public void setPath(File path){
this.path = path;

public void begin(){
System.out.println(path.getCanonicalPath()+some string);


$ / code $


解决方案

示例代码根本没有多线程。所以我假设多线程正在他们自己的 MultiThreadingClass 实例上运行,或者他们在它们之间共享一个公共实例。

无论如何,这段代码是线程安全的。唯一的共享状态是一个私有的字符串对象,不作为你的方法的一部分进行调整。

Assuming a Win32FileSystem and beginMultiThreading runs many times simultaneously on a shared MultiThreadingClass object, what is the most possible way that this can cause a data-race or some other threading issue? I know that this is probably not thread safe, because (1) the argument to setPath gets reused. I see also that (2) path is not a final variable in java.io.File. However, I can't seem to find a part where this code could error out on its own due to threading issue.

public class MultiThreadingClass {
    private Holder h = new Holder();
    private String path ="c:\\somepath"; 
    public void beginMultiThreading(){
        h.setPath(new File(path));
        h.begin();
    }
}

public class Holder {
    private File path;
    public void setPath(File path){
        this.path = path;
    }
    public void begin(){
        System.out.println(path.getCanonicalPath()+"some string");
    }
}

解决方案

Your example code has no multi-threading at all. So I'll assume that either multiple threads are operating on their own MultiThreadingClass instance, or that they are sharing a common instance between them.

Either way, this code is thread safe. The only shared state is a private string object, which is not adjusted as part of your methods.

这篇关于有这两个java.io.File线程安全问题被回避?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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