damat-perdigannat
damat-perdigannat

Reputation: 5960

Have these two java.io.File thread safety issues been evaded?

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");
    }
}

Upvotes: 0

Views: 1661

Answers (2)

kiwiron
kiwiron

Reputation: 1705

As @Duncan says, the code is currently thread-safe. But it doesn't do any file writing at this time. As you are using File objects, I have an expectation that you will be dealing with files. Once you start to write files, there are further considerations:

  • Writing to a single file from multiple threads needs to be synchronized. To my knowledge, this is not "out of the box" functionality.
  • Writing to the same file from different JVMs or even from different class loaders in the same JVM is much harder. (With most web frameworks, writing to a logging file from multiple web apps is an example of writing to a single file from different class loaders). You are back to using a lock file or a platform-specific mutex of some sort.

Caveat: It is a while since I have had to do this, so there may be more support in the latest Java concurrency package or NIO package that someone else can expand on.

Upvotes: 3

Duncan Jones
Duncan Jones

Reputation: 69329

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.

Upvotes: 1

Related Questions