Are Java FileChannel locks closed when the corresponding thread is closed, or should I explicitly close them?

For example, my code currently looks something like the following. Do I need to explicitly call lock.release or is it automatically freed when FileOutputStream 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 } 
+4
source share
3 answers

According to javadoc for FileLock :

"The file lock object is initially valid. It remains valid until the lock is released by calling the release method, closing the channel that was used to obtain it, or terminating the Java virtual machine, whichever happens first."

... and I assume that closing the stream closes the base channel.

+5
source

Imagine this being released, but curious how I was, I checked this 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 

It seems to be cleared when closing the recording.

+4
source

This question arose when I came across the same doubts.

Not finding the absolute answer, I checked several tests.

I can confirm that yes, just closing the writer will release the locks. You do not even need to manually close the stream that is under the writer.

As I tested:

1) I run the code in Eclipse in debug mode. 2) After writing and cleaning the file (before closing), I tried to delete the file using Windows Explorer. As expected, this was due to blocking. 3) As soon as I went through the writer.close () method, but before completing the execution, I again tried to delete the file. He deleted it without a problem.

This clearly tells me that the close () method will cause locks to be released.

NOTE. The above applies only to the JDK file class. Libraries that extend java.io.File can behave differently. For example, if you use the iSeries IfsJavaFile, you will have a connection memory leak if you also do not release the connection object to the iSeries server.

0
source

Source: https://habr.com/ru/post/1333639/


All Articles