0

I'd like to find a compile time solution to remove the finalize method of my classes according to a flag. This is to avoid performances issues with GC.

My build system is ANT.

Basically, I want the equivalent of this C-preprocessor macro:

#ifdef USE_FINALIZE
protected finalize() {
  ...
}
#endif

Is this possible in Java?

Community
  • 1
  • 1
ldiqual
  • 15,015
  • 6
  • 52
  • 90

4 Answers4

0

The short answer is that there is no built-in way to do this. See Java conditional compilation: how to prevent code chunks from being compiled? for more details.

However, you could potentially build a custom solution using Ant using the replace task. To do this, you could just put some magic string in comments around the blocks you want to sometimes include.

/******CONDITIONAL******

// conditional code goes here

*******CONDITIONAL*****/

Then use replace to remove those comments based on some conditional property.

Community
  • 1
  • 1
seanmk
  • 1,934
  • 15
  • 28
0

It is perhaps possible with an annotation processor (not sure at all) at compile time, using the mirror api, but it may be hard to achieve I guess.

Perhaps it is possible at Runtime too with Javassist or CGLib

Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419
0

According to the javadoc

The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.

Which means that

a) you're not doing any special finalization unless you're explicitly declaring it in your code, and

b) If you don't include a finalize() method Object.finalize() will be called, which is no-op. So you can't improve on that unless you could somehow hack the jvm to not even call finalize.

A better question might be, do you have a specific reason to worry about finalization time in your application? have you profiled this? It's entirely possible that this is a non-issue in your application.

Steve B.
  • 55,454
  • 12
  • 93
  • 132
  • As my project uses JNI, I have to release native objects in `finalize`. While I didn't benchmark this, I think it could highly decrease performances in my case (lots of jni => java calls + GC in a short time period). So according to your reference from the javadoc, the best solution is know to implement `finalize` and to rely on a static flag to perform or not the native dispose action. Great answer, that's exactly what I wanted. – ldiqual Jul 20 '13 at 03:29
0

just use java preprocessor, for instance https://github.com/raydac/java-comment-preprocessor it supports ANT and MAVEN

Igor Maznitsa
  • 833
  • 7
  • 12