Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional compilation in Java: will compiler omit "always false" blocks from class?

Tags:

java

Below is a snippet of my code:

class A { 

   private boolean debug = false;

   // Called when server boots up.
   public void init (property) { 
      debug = property.getBoolean ("debug_var"); // read debug from a config file.
   }

   // some other function  
   public void foo () { 
       if (debug) { 
                 System.out.println ("From inside the debug block");
       }
   }
 }

When I run the code, if (debug) actually prints out "From inside debug block" if debug == true in the config file.

Two Questions:

  1. So, in this case does the compiler include the if block in the .class file just because the value of variable debug might change on run time?

  2. If this is true, then how can I eliminate some code from being added to the .class file on certain environments?

like image 910
FSP Avatar asked Sep 04 '26 14:09

FSP


2 Answers

If you must do something like this, most logging frameworks have their own means of setting the level of log detail, and they just don't output any log statements that are too low-level at runtime. Use a logging framework to do this properly.

For example, with the built-in java.util.logging framework, you'd do something like

Logger.getLogger("ThisClass").log(Level.FINE, "Log message");

which only gets printed when the log level is set to FINE or below, but is ignored when the log level is CONFIG or lower.

"Conditional compilation" isn't a thing that makes sense in Java in general, but with some care, the JIT will optimize away branches it can determine will never be executed.

like image 74
Louis Wasserman Avatar answered Sep 07 '26 03:09

Louis Wasserman


The closest you can come is by using a static variable, which is useless (essentially) at run-time.

However, in your example, the JVM will likely optimize it away after it's been run enough times, so if your concern is run-time efficiency, it's likely not worth worrying about.

Ultimately I'd ask why you want to remove code from the class file based on an environment--if it's not something that can change at run time then your best option would be to create some form of pluggable implementation that can be determined/injected at runtime.

like image 43
Dave Newton Avatar answered Sep 07 '26 04:09

Dave Newton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!