finalize() called on strongly reachable objects in Java 8

前端 未结 2 1209
眼角桃花
眼角桃花 2020-11-22 08:21

We recently upgraded our message processing application from Java 7 to Java 8. Since the upgrade, we get an occasional exception that a stream has been closed while it is b

2条回答
  •  醉梦人生
    2020-11-22 09:01

    Your finalizer isn't correct.

    Firstly, it doesn't need the catch block, and it must call super.finalize() in its own finally{} block. The canonical form of a finalizer is as follows:

    protected void finalize() throws Throwable
    {
        try
        {
            // do stuff
        }
        finally
        {
            super.finalize();
        }
    }
    

    Secondly, you're assuming you are holding the only reference to m_stream, which may or may not be correct. The m_stream member should finalize itself. But you don't need to do anything to accomplish that. Ultimately m_stream will be a FileInputStream or FileOutputStream or a socket stream, and they already finalize themselves correctly.

    I would just remove it.

提交回复
热议问题