I am using Java to modify remote files in different machines by ssh. At the same time, only one thread is allowed to modify the file in one machine.
I implement the logic like this:
public boolean executeCmd(String ip, String command, String file) throws Exception
{
final String file = ip + " " + file;
final String fileLock = file.intern();
synchronized (fileLock)
{
logger.debug(Thread.currentThread().getName() + " " + fileLock + " get the lock");
SSHClient sshClient = new SSHClient();
// code to ssh to modify the file.
logger.debug(Thread.currentThread().getName() + " " + fileLock + " release the lock");
}
}
Then this function is called in tasks for multi-threads. Is this method satisfied for the purpose? I tested it for some simple cases and it seems to work OK.
At first, I lock the file using shell like this:
lockdir="$1.lock"
while ! mkdir "$lockdir" >/dev/null 2>&1
do
echo "another process is running, wait..."
sleep 10
done
trap 'rm -rf "$lockdir"' 0
There is a problem about this way. If the shell exits unexpectedly, the $lockdir will not be deleted, and it becomes a "deadlock".
I can't solve the problem so I lock the file using Java to ensure only one thread is modifying the same file.