I want to lock a remote file with the string “ip + filename” using java.
public boolean execCmd(String ip,String filename, String command)
{
String file = ip + filename;
String lock = file.intern();
try
{
synchronized (lock)
{
System.out.println(file + "get the lock");
// ssh to remote machine and exec command
System.out.println(file + "release the lock");
}
}
catch(Exception e)
{
}
}
this function is called by multi-threads, but I found the execution is a little slow, it seems to be sequential even for different files.
Now the result is like this:
file1 get the lock
file2 get the lock
file3 get the lock
file1 release the lock
file2 release the lock
file3 release the lock
file4 get the lock
file4 release the lock
file5 get the lock
file5 release the lock
file6 get the lock
file6 release the lock
...
the first three log output seems to be concurrent, but the following task seems to be sequential, I tried for many times, the result is almost the same.
Is this a normal result? or there is something wrong with the program?
Your code is right, but the synchronized on String.intern() is not a good idea.
By the way, If you want to lock the file in remote machine, you can implement it in shell script. flock can be a good way to lock a file in linux.
2