Reputation: 5960
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
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:
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
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