Eg, my code looks currently something like the following. Do I need to explicitly call lock.release
or is it automatically released when the FileOutputStream
is closed?
var os:FileOutputStream = null
var writer:PrintWriter = null
try {
os = new FileOutputStream(name, false)
val lock = os.getChannel().tryLock
if(lock != null) {
writer = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(os)))
(write stuff to file)
} else {
(error stuff)
}
} finally {
if(writer != null) writer.close
os.close
}
According to the javadoc for FileLock:
"A file-lock object is initially valid. It remains valid until the lock is released by invoking the release method, by closing the channel that was used to acquire it, or by the termination of the Java virtual machine, whichever comes first."
... and I assume that closing the stream closes the underlying channel.
Imagined it would be released, but curious as I was I checked it with this in the finally block:
println("Lock: " + lock.isValid)
if (writer != null) writer.close
println("Lock: " + lock.isValid)
os.close
println("Lock: " + lock.isValid)
And this was the result:
Lock: true
Lock: false
Lock: false
Seems it get cleaned when you close the writer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With