5

When going through the Requirements of a JAX_WS Endpoint, I came across this,

JAX-WS endpoint implementation class must not implement `finalize()` method.

But i didn't find a better answer explaining this. Why shouldn't we implement finalize() method and if we implement what happens?

Can someone please throw light on this ?

Srikanth Sridhar
  • 2,317
  • 7
  • 30
  • 50

1 Answers1

3

As you explained, the JAX-WS endpoint should not implement the finalize method (Check this).

Why?

The finalize method execution is not guaranteed by the JVM. In theory, the finalize method will be called when the object is garbage collected, but when it will be collected? There is no way to know: sometimes it will be collected right away, maybe it will be alive until the JVM stops (this mean never). Actually, this is related to the GC algorithm, and each JVM have its own implementation(s) and each one of them are very different, because there is no specification for the behavior of this algorithm.

But the real problem is that some java programmers doesn't know this, and they use the finalize method as a 'destructor'. An example: You have a class that creates a JDBC connection in its constructor. So, to make it nice you decide to release this connection in the 'destructor' (finalize). Consequence: You do not know when the connection will be closed, or maybe it will never be closed!!!

This is why implementing the finalize method is considered a bad practice for ANY java class and in some frameworks is forbidden to avoid misunderstandings (i.e. JAX-WS).

IMHO, this method should be removed from the Object API, but it still there ... maybe for backward compatibility or a useful usage that I cannot imagine ;-)

Check this for read more opinions around the finalize implementation.

Community
  • 1
  • 1
ggarciao
  • 1,618
  • 16
  • 29
  • Thanks a lot. I have one more question as you explained about GC algorithm, what exactly do you mean when you say that there is no specification for the behavior of the GC algorithm ? – Srikanth Sridhar Jul 17 '12 at 06:58
  • *Java Virtual Machine* is not a software but an specification (http://docs.oracle.com/javase/specs/jvms/se7/html/index.html). This spec depict what a JVM should do. Then each implementor (Oracle Rockit, IBM JVM, Sun/Oracle JVM) will follow this spec to create the real thing. If you have the time to read a little, you will see that there is no spec that define how memory management and garbage collection should be implemented. For this reason, each JVM provider have different ways to manage memory and its own GC algorithms. – ggarciao Jul 17 '12 at 07:43