Don't use floats for money

Did you ever try this?

float total = 0.0f;
Line line = new Line(0.3f, 1); // custom line object
for (int i = 0; i < 100; i++) {
  total += line.getPrice() * line.getCount();
// 0.3 * 100 = 30
System.out.println(total); // 29.999971

When this code sums 100 order lines with every line having one 0.30€ item, the resulting total is calculated to exactly 29.999971. The developer notices the strange behaviour and changes the float to the more precise double, only to get the result of 30.000001192092896.
The somewhat surprising result is of course due to the difference in representation of numbers by humans (in decimal format) and computers (in binary format IEEE 754). It always occurs in its most annoying form when you add fractional amounts of money or calculate the VAT.

double a = 1.14 * 75; // 85.5 represented as 85.4999...
System.out.println(Math.round(a)); // surprising output: 85

There are business cases where you can not afford to lose precision. You lose precision when converting between decimal and binary and when rounding happens in not a well-defined manner or at indeterminate points. To avoid losing precision you must use fixed point or integer arithmetic's. This does not only apply to monetary values, but it is a frequent source of annoyance in business applications. Consequently a non-integer amount of money should never be stored in a floating point data type. Even a simple multiplication with an integer can already yield an inexact result. If you see a float or double in your financial code base, the code will most likely yield inexact results. Instead either a string or fixed point representation should be chosen. Both representations must define the precision (number of digits before and after the decimal point) that is stored. For calculations the class BigDecimal provides an excellent facility. The class can be used such that it throws runtime exceptions if precision is unexpectedly lost in an operation. This is very helpful to uproot subtle numerical bugs and enables the developer to correct the calculation. Once the calculations and rounding are done, you can safely use the NumberFormat objects and methods to format the BigDecimal objects for display.

But there are some pitfalls...
The results of constructor that takes a double can be somewhat unpredictable. One might assume that new BigDecimal(.1) is exactly equal to .1, but it is actually equal to .1000000000000000055511151231257827021181583404541015625 This is so because .1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to 0.1 The (String) constructor, on the other hand, is perfectly predictable: new BigDecimal(".1") is exactly equal to .1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one. BigDecimal supports the use of the compareTo method for comparing values. In most cases you will want to use the compareTo even for equals comparisons because the equals method considers two numbers with the exact same value but different scales to be not equal. In other words, the equals method considers 2, 2.0, 2.00, and 2.000 to be different numbers. The compareTo will consider all of them to be equal!

BigDecimal total = new BigDecimal("0"); // BigDecimal.ZERO exists since JAVA 1.5
for (int i = 0; i < 100; i++) {
  BigDecimal price = new BigDecimal(line.getPrice());
  BigDecimal count = new BigDecimal(line.getCount());
  total = total.add(price.multiply(count)); // BigDecimal is immutable!
total = total.setScale(2, BigDecimal.ROUND_HALF_UP);

// remark if you use 1.14 as a type float as input the answer will still be
// bad one, using the String type resolves this!
BigDecimal a = (new BigDecimal("1.14")).multiply(new BigDecimal(75));
// 85.5 exact
a = a.setScale(0, BigDecimal.ROUND_HALF_UP);
System.out.println(a); // correct output: 86

continue reading »

Content delivery node

When the big boys run websites they use Content Delivery Networks (CDN’s) to host their static content, static resources are assets that are delivered in the same way for every user. Examples of static resources include images, CSS, JavaScript, multimedia, Flash scripts, and so forth. . The reason they do this is that the less they have to host themselves the less load they have on their servers, and the more content they can host closer to the end user the quicker the user can download it.

But thanks to Google anyone can now run their own CDN for free on Googles servers....

Lets have a quick look on how to do this (The JAVA way)

  1. Create an empty Google app engine project.
  2. Remove all JAVA code
  3. Create all the static content you need in the war directory
  4. Put following 2 files in the WEB-INF directory


<?xml version="1.0" encoding="UTF-8"?>
         <web-app xmlns=""
         xsi:schemaLocation=" "


<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="">
        <include path="/**.*" />

5.  Upload it to GAE.


You now have your own private CDN! (For FREE)
Go to <your-application-identifier>

continue reading »


Let’s have a look at the synchronized keyword in 3 different ways - synchronized class methods, synchronized instance methods, synchronized statement blocks. Java offers a synchronization monitor on each instance of Object, so all objects in Java can be used as a synchronization lock.

Synchronized Class Method:

class Test1 {
   public static synchronized Object myStaticMethod() {
      // put your code here

All the statements in the method become the synchronized block, and the class object is the lock.

Synchronized Instance Method:

class Test2 {
   public synchronized Object myMethod() {
      // put your code here

All the statements in the method become the synchronized block, and the instance object is the lock.

Synchronized Statement:

class Test3 {
   public Object myMethod() {
      synchronized (object) {
         // put your code here

All the statements specified inside the parentheses of the synchronized statement become the synchronized block, and the object specified in the statement is the lock. This is the recommended way to manage your synchronized blocks.

This is where the magic happens:

When a synchronized block is called, it will try to gain the ownership of the monitor of the lock. If another thread currently owns the lock's monitor, it will wait. Once the lock's monitor is free, the waiting thread will take possession of the lock's monitor, and start to execute the synchronized block. Once the synchronized block is executed to the end, the lock's monitor will be free again. Note that one Object can have many locks and each lock can be associated with many different synchronized blocks. For example, the following Object defines two synchronized operations. Both are associated with the same lock, the instance object.

class Test4 {
   public Object myMethod() {
      synchronized (this) {
         // put your code here
   public synchronized Object myMethod2() {
      // put your code here

myMethod() will never be executed at the same time as myMethod2(). The following code also defines two synchronized operations. But they are associated with two different locks, one is the class object, and the other is the instance object. Those two synchronized operations will never wait for each other.

class Test5 {
   public type Object myMethod() {
      synchronized (this) {
         // put your code here
   public static synchronized Object myStaticMethod() {
      // put your code here

Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error.

Re-entrant Synchronization

Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once is called re-entrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock.

continue reading »

Mobile pages

When trying to improve a prototype mobile site, to work better on the iPhone. I had some problems with the some of the pages being too wide for the device. It took me a while to figure out the solution, but here’s what I found:

The magic is just in one line of code in the head of your html:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">

This can causes some problems though, as CSS’s set width seems to take precedence over that meta tag’s “width=device-width” and the page comes out too large.

So if you need to set width in you CSS, your next step will have to be to use a device specific CSS, like this:

<link media="only screen and (max-device-width: 480px)" href="iPhone.css" type="text/css" rel="stylesheet" />

continue reading »

Thread Safe DateFormat

The problem with this class and SimpleDateFormat is that it has a state and if you have two or more threads calling methods on the same instance you could get results you would not expect. The simplest fix for the concurrency problem is to create a new instance each time as needed. But DateFormat is a complex Object to create, so many of us are tempted to create it like this:

private static final SimpleDateFormat DF = new SimpleDateFormat("dd-MMM-yyyy");

If you decide to do this don’t forget to make all the calls to format() in a synchronized way:


public String formatDate(Date date){
  String result="";
  synchronized (DF) {
    result = DF.format(date);
  return result;

Happy coding,

continue reading »