Re: JavaMemoryModel: A problematical case for finalizers

From: Jerry Schwarz (jerry.schwarz@oracle.com)
Date: Tue May 20 2003 - 15:47:30 EDT


At 12:04 PM 5/20/2003, Joshua Bloch wrote:
>Hans,
>
> No worries. I didn't think that you were referring to my book:) I
> agree that there's lots of very bad advice floating around out there
> concerning finalizers. But I simply wouldn't go out of my way to make it
> any easier to write corect finalizers. Very few people should have to
> write them, and those who do should understand the issues.

Out of curiosity I checked the code that ought to have been written by some
of the "few people who should have to write them". Specifically the JDK
(1.4) source for FileOutputStream (

     protected void finalize() throws IOException {
         if (fd != null) {
             if (fd == fd.out || fd == fd.err) {
                 flush();
             } else {
                 close();
             }
         }
     }

     public void close() throws IOException {
         if (channel != null)
             channel.close();
         close0();
     }

Notice there is no synchronization here. Indeed there is no
synchronization at all in FileOutputStream. Except for the presence of
natives (like close0) to manipulate the OS resources this is pretty
ordinary looking code. Are natives special within the memory model (I don't
remember)? This is clearly a place where a finalizer is needed.

If we assume that it is ok to call the native close0(), and Channel.close()
multiple times and from multiple threads simultaneously then what can we
say about this code? It still seems to be all the "normal" problems that
we have been worried about: premature calling of finalize and updates of
the fields not getting propagated to the finalizer thread.

This reinforces my sense that we need to fix the finalizer model to work
with this kind of code.

> >5) There's no clear convention about the context in which finalizers can be
> >explicitly invoked. If System.runFinalization() runs finalizers in the
> calling
> >thread,
> >
>It can't! One of the few hard guarantees is that finalizers are run from
>a thread that holds no user-visible locks. (I say this from memory, but
>I'm quite sure it's in the spec.)
>
> Regards,
>
> Josh
>
>
>-------------------------------
>JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel

-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:44 EDT