What’s The Deal With Half Up and Half Even Rounding?

java.math package came with several rounding mode but there are 2 quite interesting ones: HALF_UP and HALF_EVEN rounding.

HALF_UP

This is basically your elementary school rounding. If the fractions to be rounded are equidistant from its neighbor, then round them into the upper neighbour. In other words, if we’re rounding 1 digit after decimal, then if it ends with .5 just add .5. For example:

Fractional Number Rounded
0.1 0
0.5 1
1.3 1
1.5 2

HALF_EVEN

Similar like HALF_UP, except if the fraction is equidistant, round them into nearest even neighbor. For example:

Fractional Number Rounded
0.1 0
0.5 0
1.3 1
1.5 2

Why Bother With HALF_EVEN?

Why don’t we just stick with what’s learned in elementary school? Well here’s one good reason: accumulative error. Error here means “How much did we lose/gain by rounding the number?”. Let’s take a look again to both table with its rounding error displayed

Fractional Number HALF_UP rounding HALF_UP rounding error HALF_EVEN rounding HALF_EVEN rounding error
0.0 0 0.0 0 0.0
0.1 0 -0.1 0 -0.1
0.2 0 -0.2 0 -0.2
0.3 0 -0.3 0 -0.3
0.4 0 -0.4 0 -0.4
0.5 1 0.5 0 -0.5
0.6 1 0.4 1 0.4
0.7 1 0.3 1 0.3
0.8 1 0.2 1 0.2
0.9 1 0.1 1 0.1
1.0 1 0.0 1 0.0
1.1 1 -0.1 1 -0.1
1.2 1 -0.2 1 -0.2
1.3 1 -0.3 1 -0.3
1.4 1 -0.4 1 -0.4
1.5 2 0.5 2 0.5
1.6 2 0.4 2 0.4
1.7 2 0.3 2 0.3
1.8 2 0.2 2 0.2
1.9 2 0.1 2 0.1
2.0 2 0.0 2 0.0
Total 1 0 0

As you can see the accumulative errors for HALF_UP is incrementally higher whereas HALF_EVEN averages out. This is why HALF_EVEN is often called “Banker’s rounding” because given a large amount of data the bank should not gain/loss money because of rounding.

More Surprises With printf

Don’t yet assume all programming language defaults into HALF_EVEN, try below examples of printf in your shell:

$ printf "%.5f" 1.000015
1.00002
$ printf "%.5f" 1.000025
1.00002
$ printf "%.5f" 1.000035
1.00004
$ printf "%.5f" 1.000045
1.00005

Wait.. what? Isn’t 1.000045 supposed to be rounded to 1.00004? Well in floating point realm the reality is more complicated than that, taking into account floating point is often never accurate in the first place.

Try printing 1.000045 with long enough digits after decimal:

$ printf "%.30f" 1.000045
1.000045000000000072759576141834

Now you can see computers can’t always store accurate value of real numbers in floating point types. (And you should now see why it’s rounded into 1.00005)

Here’s some reading if you’re interested in this problem.

Using File Protocol to Deploy Maven Project To Windows Shared Folder

Our development team is fairly small and we’re not at the point where we need Nexus yet, so I decided we can try using a simple Windows server share as our internal Maven repository.

On each of our shared Maven project pom.xml we add following distributionManagement configuration:

<distributionManagement>
  <repository>
    <id>enfinium</id>
    <name>Enfinium Internal Repository</name>
    <url>file://mavenrepo/maven_repository</url>
  </repository>
</distributionManagement>

Where //mavenrepo/maven_repository is the Windows server share we’ve setup. We’ve made sure each team member has correct read/write permission.

However every time we deploy Maven would say everything is successful but the file is nowhere to be found on the remote repository. (We’re using Maven 3.1.0

Turns out with file protocol and Windows server share, this is the syntax that works for us (yes Maven just fail silently and said everything was SUCCESSFUL)

file://\/\/mavenrepo/maven_repository

Debugging Maven Unit Test in Eclipse / STS

Maven unit tests (run by surefire plugin) can be debugged with eclipse. Firstly check you’re using surefire plugin version 2.16 or newer. Observe / add following in your pom.xml

<plugin>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.16</version>
</plugin>

Ensure you’ve set some breakpoints to debug the faulty codes. Then on your run configuration, add -Dmaven.surefire.debug=true parameter:

maven-debug1

When this run configuration is executed, maven will wait for you to attach the remote debugger instead of launching the tests:

maven-debug2

Now open eclipse debug configuration, create a Remote Java Application config with your source code and set the port to 5005:

maven-debug3

When the debugger attaches the unit test will proceed and when any breakpoints hit you can debug it like a normal java/eclipse application

Debugging Event Driven Multithreaded Java Code

So here’s the scenario: you have few potentially time consuming work need to be done. They need to be executed in the order of submission, but only one work at a time can run. Simple solution is to use single thread executor.

First let’s define the Job class. This is a simple class implementing Runnable, when the job runs / stops it will print to console. A random sleep between 1 to 5 seconds is introduced to simulate some reality.

public class Job implements Runnable {

  private String id;

  public Job(String id) {
    this.id = id;
  }
  
  @Override
  public void run() {
    System.out.println("Job " + id + " started");
    
    long duration = (new Random(System.currentTimeMillis()).nextInt(5) + 1) * 1000;
    try {
      Thread.sleep(duration);
    } catch (InterruptedException e) {
      System.out.println("Job " + id + " interrupted");
      e.printStackTrace();
    }
    
    System.out.println("Job " + id + " completed");
  }

}

To run the job I have a JobRunner class that setups the ExecutorService. Just call submit(job) and the job will be queued and run when the worker thread is free.

public class JobRunner {

  private ExecutorService executor = Executors.newSingleThreadExecutor();

  public void enqueue(Job job) {
    executor.submit(job);
  }

}

But a debugging problem starts to appear. It is now obscure where does the code goes after calling submit()? Which thread runs it? Unless the programmer put a big comment informing it is actually a Runnable this could be very hard to guess.

Further Problems with Observer Pattern

Another common patterns often used is the observer pattern. The idea is you want specific objects to “react” when a particular event occured.

For example, let’s do two observers: OddJobObservers and EvenJobObservers. When an odd/even job completed the corresponding observer will print to console.

public class OddJobObserver implements Observer {

  @Override
  public void update(Observable arg0, Object arg1) {
    int id = (int) arg1;
    if(id % 2 == 1)
      System.out.println("Odd job " + id + " completed");
  }

}
public class EvenJobObserver implements Observer {

  @Override
  public void update(Observable o, Object arg) {
    int id = (int) arg;
    if(id % 2 == 0)
      System.out.println("Even job " + id + " finished");
  }

}

For this purpose we’ll refactor JobRunner to extend Observable so we can add the observers into it. The observer instances are created and registered on the constructor.

Each time a job is created it will also have reference back to JobRunner. We’ll also add a method jobFinished(int id) for the job to call when it’s done running.

public class JobRunner extends Observable {

  private ExecutorService executor = Executors.newSingleThreadExecutor();

  public JobRunner() {
    addObserver(new OddJobObserver());
    addObserver(new EvenJobObserver());
  }

  public void enqueue(Job job) {
    job.setJobRunner(this);
    executor.submit(job);
  }

  /**
   * This will be invoked by the Job's run method in the worker thread
   * to indicate the runner that this particular job is finished
   */
  public void jobFinished(int id) {
    setChanged();
    notifyObservers();
  }
}

And on the Job class once it’s finshed running we’ll notify the observers

public class Job implements Runnable {

  // ...
  
  @Override
  public void run() {
    System.out.println("Job " + id + " started");
    
    // ...

    System.out.println("Job " + id + " completed");
    jobRunner.jobFinished(id);
  }

}

Consider debugging this code where you’re at the end of run() method which takes you to jobFinished(). It is now even more obscure because notifyObservers() is a Java API method, not your own code. Which code gets executed next?

Unless you did a good job on commenting, it’s very hard for someone reading your code to understand that at that point odd jobs will be observed by OddJobObserver and even jobs / EvenJobObserver.

The problem gets much worse with production client / server application with 50+ observers handling different scenario.

One approach is probably to put breakpoints on every single observers and see which one is actually “interested” in our event.

I hope this highlights how important properly commenting your code is (especially for your poor colleague who has to fix your code sometime in the future).

Java and XML Injectable Properties on Spring

Here’s how you can create a property file which can be injected on Java classes as well as on bean XML configuration file.

Firstly ensure annotation config is switched on:

<context:annotation-config/>

Create your properties file, in this case I create config.properties on my classpath root (src/main/resources/config.properties on Maven-compliant project)

name=Gerry

Register this property file on your spring context using <util:properties> tag. The file will be registered as a bean class with name config

<util:properties id="config" location="classpath:/config.properties"/>

Whenever you want to inject the value into a Java class, you can use @value annotation

@Component
public class Person {

  @Value("#{config.name}")
  private String name;

  //...
}

Similarly you can do the same to xml bean config file

<bean class="my.app.Person">
  <property name="name" value="#{config.name}"/>
</bean>

Note that if you config has dots on it, you need to use the square bracket syntax or Spring will confuse the dot as property access

@Value("#{config['first.name']}")
private String name;

Multiple Environment Trick

Another trick I love is specifying multiple environment config, eg: one for prod and dev. This is common when dealing with datasource properties:

dbhost=localhost
dbhost.dev=192.168.0.20

On dev environment, I then supply -Denv=dev system property to my VM args, and do this when looking up the property:

@Value("#{systemProperties['env'] == 'dev' ? config['dbhost.dev'] : config['dbhost']}")
private String databaseHost;

Putting String List on Properties

Property files can also hold simple string list:

emails=gerry@test.com,tom@wohoo.com

When injecting this, use the split() method. Becareful with whitespaces you placed as it will be carried over

@Value(#{config['emails'].split(',')})
List<String> emails;

Returning JSON View on Spring MVC

Another simple way to return JSON object is by using jackson-mapper-asl. Similar to how we can map server-bound post, this method can also be used to write response.

Firstly, on your Spring MVC enabled project, add following maven dependency:

<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-mapper-asl</artifactId>
  <version>1.9.12</version>
</dependency>

Spring can automatically convert your POJO into a json string. So say we have this data object we want to return:

public class Customer {
  private String name = "";
  private String email = "";
  // getters & setters...
}

And this is the controller request mapping method. Important bits here is the method returns a POJO object directly, and it is annotated with @ResponseBody annotation.

@RequestMapping("/customer/{id}")
@ResponseBody
public Customer getCustomer(@PathVariable("id") long id) {
  Customer customer = // Search customer by given id through repository..
  return customer;
}

On the client side the returned JSON will be something like this:

{
  name = "Tom",
  email = "tom@someprovider.com"
}

Prevent Tomcat From Locking WAR Files

Sometimes when Tomcat is running, although you’ve set autoDeploy to false the server process still hold file locks into the war / folder. This can be prevented by setting antiResourceLocking attribute to true on your context.xml. However the documentation said this setting might cause other issue so use it with care: http://tomcat.apache.org/tomcat-7.0-doc/config/context.html