Ok, new to java questions. 1) I'm a little confused about if/when explicit close() is needed. I've seen code like:
where nothing explicitly is done with the file except that temporary FileOutputStream. If I had a reference to the FileOutputStream and kept it around for a while, would I need to close() it to make it available for other threads/processes? Seems like when I getChannel() it is locked to other applications until I close the channel.
2) The bigger question, how do I lock a (Properties) file, read it, change it, and write it back? I'm stuck because Properties.load() and Properties.store() use FileInputStream and FileOutputStream respectively and I can't seem to tie them together. If I FileLock the FileOutputStream, then I can't read it with FileInputStream. I want to hold the FileLock across load() and store(). Here's an attempt.
Joined: Mar 30, 2005
I suppose a solution to my problem, although not a specific answer to my question, is to lock some other file like: c:\user\test\file.lock and hold it while I process c:\user\test\file.properties. That works if everyone cooperates and follows the same scheme. Doesn't stop some other application (notepad) from openning it but that's unlikely anyway.
Also, although it probably doesn't matter, I didn't explain my requirements for what I'm doing. I'm using a Singleton class synchronized method to protect the load/store within a single JVM. But I have a requirement to protect the load/store across JVM's so I started looking at FileLock.
I haven't played with file locks yet, but from my reading of the JavaDocs and going through the tutorial, the lock is acquired on the file itself -- not its channel. Removing your second lock attempt should solve the problem.
Note that even if it was the file's channel that was locked, won't the input and output stream both point to the same file channel? Again, it should matter, but you might want to check it out to better your understanding.
Joined: Mar 30, 2005
No, originally I didn't have that second tryLock() in the code, you can ignore it. It's the Properties.load(fis) that fails. I added the second fisChannel.tryLock() hoping I could get a lock on the fis but it comes back null and the load(fis) still fails.
I thought getting a FileLock isn't supposed to prevent the same thread (or even another thread in the same JVM) from getting the lock again. But it does and it's odd that it complains that another "process" holds the lock.
Well, I was hoping from my reading that both the fis and the fos used the same channel/lock but that's not what I seem to be experiencing.
subject: FileLocks and FileInputStream/ FileOutputStream