Tag Archives: java

Double check locking in Java

We all know the double check locking bug in Java right?

Noticed this issue in one of our static singleton constructors.

public static FXRateService getInstance() {
        if (fxRateService == null) {
		synchronized(FXRateService.class) {
			if (fxRateService == null) {
				fxRateService = new FXRateService();
			}
		}
	}	
	return fxRateService;
}

This is a particular problem, if getInstance() is accessed by two threads, there is a chance that the FXRateService returned will be uninitialised. One of the known solution would be simple to create the service eagerly, via a static declaration statement.

My boss however, from a .net background came up with another solution involving adding an additional boolean to signal the thread.

private static boolean ready = false;
public static FXRateService getInstance() {
        if (!ready) {
		synchronized(FXRateService.class) {
			if (!ready) {
				fxRateService = new FXRateService();
				ready = true;
			}
		}
	}	
	return fxRateService;
}

He argues that this way, the 2nd thread will always wait until the boolean becomes true before proceeding to the synchronized code. This seems to make sense at first glance, however due to the way Java Memory model works, it is still not correct.

Though the synchronized block guarantees only one thread will enter the block at one time, the order of execution can still be reordered by the compiler depending on the implementation of the JVM. It is entirely possible for ready == true before fxRateService is properly initialised.

Tagged ,

Subtle equals bug in Java

The findbugs fairy discovered a little issue in my projects.

Bug: com.bfm.appl.blimp.marketdata.FXPricingSecurity overrides equals in PricingSecurity and may not be symmetric
Patternid: EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC, type: Eq, category: CORRECTNESS

This class defines an equals method that overrides an equals method in a superclass. Both equals methods methods use instanceof in the determination of whether two objects are equal. This is fraught with peril, since it is important that the equals method is symmetrical (in other words, a.equals(b) == b.equals(a)). If B is a subtype of A, and A’s equals method checks that the argument is an instanceof A, and B’s equals method checks that the argument is an instanceof B, it is quite likely that the equivalence relation defined by these methods is not symmetric.

Clear as mud? Let’s have a look at an example:

Continue reading

Tagged ,

Jacob and Excel

I’ve recently have to do some Excel integration with Java.

It was a very interesting challenge, I had to play around with COM and Dispatch stuff, things I have never touched before from a pure Java world.

After some investigation with the different libraries available, I’ve decided to try it Jacob. One of my requirements was to be able to read the data from Excel’s spreadsheet in memory, these data could have been altered constantly from external sources without been saved to to file system.

Using Jacob I was able to read all the workbook’s title, worksheets within the workbook, and the cells and their data all in memory. Basically anything functions from the Visual Basic editor within Excel was available from the Jacob’s API.

Continue reading

Tagged , ,

Proxying object for fun and profit

Got a little performance issue, fired up the profiler and tracked 75% of CPU cycle on this block of code.

public int indexOf(ReportColumn col, UseType use) { 
  ReportColumn copyColumn = col.copy(); 
  copyColumn.setUse(use); 
  return columnList.indexOf(copyColumn);
}

The majority of the hold up is in the copy() function which produce a deep clone of the ReportColumn object via reflection. Not only is this very slow, but it also increase the memory needed because of the deep clone process.

My immediate reaction was to use remember the “use” value of the column, make a change to the col object, find the index and change it back. But then I started to worry about the original intent of the function, since I didn’t write it, I just assume whom ever did write it this way must use deep cloning for a reason. Maybe they expect col object to be read by another thread while the search is happening. Hence I just abandoned plan A.

Plan B involved proxying, and went a bit like this.

public int slowIndexOf(ReportColumn col, final UseType use) { 
  ProxyFactory pf = new ProxyFactory(); 
  pf.setTarget(col); 
  pf.addAdvice(new MethodInterceptor() {  
    @Override  public Object invoke(MethodInvocation mi) throws Throwable {   
      if (mi.getMethod().getName().startsWith("getUse")) {
        return use;   
      }  
      else {
        return mi.proceed();
      }
     }
   }); 
   ReportColumn copyColumn = (ReportColumn) pf.getProxy(); 
   return columnList.indexOf(copyColumn);
}

By using the spring’s inbuilt proxying libraries, I constructed a method interceptor to intercept call to getUse and replace the value with the use we want to search for.

However, as the name indicates, it was very slow, slower than I thought it would be, in fact pf.getProxy() was 4 times slower than the deep clone method.

Back to the drawing board, I ended up tracing the code to see if I can find any potential code that might be reading the col object while it is been used, hoping that I can try a locking to prevent that from happening. As it turns out, there is no concurrent access. So I ended up with this.

public int indexOf(ReportColumn col, final UseType use) {
  UseType oldUse = col.getUse(); 
  col.setUse(use); 
  int index = columnList.indexOf(col); 
  col.setUse(oldUse); 
  return index;
}

Lesson here, first instinct/simplest solution is often the best, also question your initial assumptions.

Tagged , ,

Strange Generics in Java

So I had an interesting issue in my new project today.

Th cause of the bug is not that strange itself, what essentially happened was that a Hibernate mapping was missing in one of the project’s shared libraries. This caused the query that was suppose to return a collection of the domain objects to instead return a collection of map objects.

So far, totally understandable behavior. But it’s how I found out about this bug that was unusual.


Collection<Domain> objs = daoImpl.getDomains(); // was actually returning a collection of maps
if (objs != null) {
  for (Domain d : objs) {
    //do something with d    
  }
}

This is roughly the code I had that used the share library. I had expected the InvalidCastException to be thrown at line 1. However it was not until line 3 when the for loop was executing before Java detected that something was wrong.

To be sure of this I even stepped the code through the debugger, yep, I can clearly see that it was a Collection of maps, and it is definitely not picked up until the for loop.

It was driving me crazy, I even entertained the thought that maybe java.util.Map secretly inherited my domain object somehow.

Then it suddenly hit me, Java generic type checking is enforced only at compile time. Since Hibernate is creating the domain objects by reflection, the compiler couldn’t possibly have known the class mismatch.

Lesson to remember, beware when pulling in new shared library.

Tagged ,

Log debug and Hibernate, a tale of two environments

Cute story.

A couple of years back I got a call for support with a recently released webapp. User is complaining that a particular functionality was returning the following hibernate exception.

org.hibernate.LazyInitializationException: could not initialize proxy – the owning Session was closed

A quick source check have indeed shown that the field in question was lazy initialised when it should not have been. But the puzzle remains, it worked in UAT environment. In fact it was extensively tested by the particular user who reported the issue before it was released into production. Not to mention all the developer testing that was done.

The simple explanation would be, we simply missed that particular functionality when we did the test. But that was soon ruled out as in UAT, the bug was still not rearing it’s ugly stack trace. So, what was it in production that is making it fail?

As it turned out, the correct question should be, what was in UAT that made it work? This:

if (logger.isDebugEnabled()) {    
  logger.debug(dataMap.toString());
}

The reason it was working UAT was because log was set to debug in that environment, while in production it was set to info only. Having the dataMap.toString() called in that debug block means hibernate actually went and fetched the lazy initialised data, as oppose to in production where the first time the code needed dataMap, the hibernate session was already closed.

I’m still not sure what exact lesson I should take away from this, but it sure was an interesting code mystery.

Tagged ,

Android “Fling” Gesture Detection

Had some issues last night trying to get my Android game to detect the fling gesture, basically a click and drag in mouse world.

I had the following code in my little View object.

private GestureDetector gestureDetector;
private View.OnTouchListener gestureListener;// Gesture detection
    gestureDetector = new GestureDetector(new MyGestureDetector());
    gestureListener = new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if (gestureDetector.onTouchEvent(event)) {
                return true;
            }
            return false;
        }
    };
this.setOnTouchListener(gestureListener);

  * Handle any fling action here
  * @author dracox
  *
  */
 protected class MyGestureDetector extends SimpleOnGestureListener {
  /**
   * We need to capture any user line drawn request here.
   */
  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
   //This should only be caring about flings after init
   gameWalls.add(new FireWall(new Point((int)e1.getRawX(), (int)e1.getRawY()), new Point((int)e2.getRawX(), (int)e2.getRawY())));
   return true;
  }
 }

I fired up my emulator, but was not getting any fling action logged. However the onTouch events were been fired off.

Initially I though maybe the emulator couldn’t handle fling event, but after much searching I found the root of the problem.

Apparently, the onDown event was fired off first, which was consumed before it became a “fling”, so I had to override that too on my custom Gesture Detector class.

I was a little puzzled about returning true for the onDown handler, as the API stated return true to consume the event and false to let it pass.

/**
 * Need to let onDown pass through, otherwise it will block the onFling event
 */
 @Override
 public boolean onDown(MotionEvent event) {
 return true;
 }

Now we’re flinging!

Tagged , ,