Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

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?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
OK, I lock the file in shell at last, but I don't use the flock, I use the mkdir instead. –  NingLee Nov 10 '14 at 5:02
    
@NingLee flock is a more official way anyway. –  shangyin Nov 10 '14 at 5:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.