2

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?

1 Answer 1

1

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
  • OK, I lock the file in shell at last, but I don't use the flock, I use the mkdir instead. Commented Nov 10, 2014 at 5:02
  • @NingLee flock is a more official way anyway. Commented Nov 10, 2014 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.