Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Java FileChannel locks closed when the corresponding Stream is closed or do I have to explicitly close them?

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
}
like image 293
Jackson Davis Avatar asked Jan 21 '23 20:01

Jackson Davis


2 Answers

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.

like image 180
Stephen C Avatar answered Feb 01 '23 17:02

Stephen C


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.

like image 39
thoredge Avatar answered Feb 01 '23 15:02

thoredge