Sub-millisecond Java

November 19th, 2008

Imagine you had to implement (complex) code in Java that runs in sub-millisecond time. How will you know that you’ve succeeded? The traditional measurement such as this one won’t work.


long before = System.currentTimeMillis();
doSomeWork();
long elapsed = System.currentTimeMillis() - before;
// check that elapsed < 1

This is not great. It turns out that the operating system’s tick measurement greatly depends on the platform. On the Intel platform, the OS uses the default timer, which ticks 128 times a second. That means that the timer resolution will be roughly 8 ms. Not great. We need something far more accurate.
It turns out that on Intel CPUs (Pentium and above), you can use the RDTSC instruction that returns the number of processor ticks since power-up as 64bit number. “Aha!”, you say, “this is it.” The trouble is that the ticks are relevant only to the CPU on which the code is running. On a multi-processor system, the thread can run on any CPU and the CPUs do not have the same number of ticks. Dang!

OS functions

Your only option is to use the functions of the operating system. On Windows, you can call QueryPerformanceCounter(); on UNIX, you can use gettimeofday(...). These methods will give you roughly microsecond accuracy, which is usable for measuring sub-millisecond code.

Measuring critical code

The catch is that the impact of the measurement code can distort the numbers. The way around it is to calculate the measurement time overhead (per call, using compile- or load-time weaving) and then record the performance and the number of calls. Then you can subtract the expected overhead from the measured value, giving you reasonably accurate number.

AOP

Let me give you head start:


@Aspect
public class PerformanceMonitoringAspect {
    private final long THRESHOLD = 500L;  // 500 ns
    private final long callCount = 0;

    @Pointcut("execution(* net.cakesolutions.citi..handler.*.*(..))")
    private void handlerMethodExecution() { }

    @Around("handlerMethodExecution()")
    public Object performanceCollector(ProceedingJoinPoint pjp) throws Throwable {
        this.callCount++;
        long start = HighPerformanceTimer.getNanoTime();
        try {
            return pjp.proceed();
        } finally {
            long elapsed =
                (HighPerformanceTimer.getNanoTime() - start) -
                callCount * 4; // call time correction
            if (elapsed > THRESHOLD) writePoorPerformanceLogEntry(pjp);
        }
    }

    private void writePoorPerformanceLogEntry(ProceedingJoinPoint pjp) {
        System.out.println("Slow!");
    }
}

If you need any more information, contact me at Cake or come over to the next Spring User Group meeting, bring some purple cauliflower and I’ll talk.

Spring User Group November 5 Minutes

November 16th, 2008

We tried a new ice-breaker for the Spring User Group meetings. It’s called “Ask Jan” — the attendees select two from a list of five topics they’d like me to talk about. Then I have some time to prepare short 5 - 10 minute talks on the selected subject.
At the SUG meeting on 12th November, the areas were:

  • Performance monitoring approaches
  • Top 3 Hibernate tips
  • Web application security
  • Five interesting applications
  • And one more thing that I can’t remember any more

From this list, the attendees selected the first two items; I have prepared a talk that covers the two topics. Download.

Manchester Wheelers’ 125th Anniversary

November 10th, 2008

On Saturday I went to the Manchester Wheelers’ 125th anniversary dinner and prize presentation. I was there to collect club standard certificates for 2nd class on 10 miles for time of 24:18, 2nd class on 25 miles for time of 1:02:52 and 3rd class on 50 miles for time of 2:10:00. I took the prize certificates to the office and will post pictures tomorrow.
P.S. I know the times are rubbish, but I never ventured outside the “J” courses. I hear that J2/9 and J4/16 are one of the slowest courses.

Spring User Group Meeting

November 7th, 2008

It is that time of the month again — time to meet up at the Spring User Group in London. At this meeting, you will have a chance to listen to Sam Brannen speak about the dm Server and I will give introduction to the new Spring Workflow Extension.
We’re all looking forward to seeing you on Wednesday 12th November at the Skills Matter offices — all you have to do is to register.
If you are on LinkedIn, you can join the Spring User Group.

Vertically Aligning Images with jQuery

October 30th, 2008

I have often needed the to fulfil the requirement of aligning an image to the middle of a specified height. In the old table based way of doing it was pretty easy. All you needed to do was valign=”middle” on the cell containing the image. Things have changed (for the better) by dropping table based layouts. Unfortunately not all browsers CSS capabilities are good enough to align to the middle very easily.

So I came up with a solution in jQuery when working on a current project’s product gallery. Solving it programatically is alot quicker than editing every image.

All you need is:

  1. jQuery
  2. A transparent GIF
  3. And a tiny bit of jQuery magic

All you need to do is set the maximum height and width to the image that you require. Then set its background colour (if needed) as well as a background image the same as current source at 50% (both top and left). Then finally replace the current image source with the transparent GIF revealing your newly centred and middlely (new word) aligned image.

Your code should look something like this.


$(function(){
$("img.middle_aligned").each(function(){
$(this).css("width","160px").css("height","110px").css("background","#fff url("+$(this).attr("src")+") 50% 50% no-repeat").attr("src","images/blank.gif");
});
});

If you have any other techniques let me know in the comments.

Now go and make some awesome image galleries with the aid of jQuery.

Brr!

October 29th, 2008

The weather turned rather cold in Manchester. And by cold I mean freezing cold by UK standards, -1 °C. Still, the car had its weekly outing to Tesco on Sunday and probably wouldn’t start anyway, so I was on my bike.

By the time I got to the office, I had lost feeling in my ears and fingers. Breaking and changing gears became more and more difficult. I guess I’m going to have to buy thicker gloves and something for the ears.

SpringSource dm Server in Action

October 23rd, 2008

We’re excited to tell you that our new book, SpringSource dm Server in Action, is now available under the Manning Early Access Program. As you can guess, the book focuses on the dm Server and its impact on the world of Java EE programming.

What’s inside?

We start with the basics: installation of the dm Server and the Tool Suite, followed quickly by your first helloworld bundle. Then we dive into the deep waters of the dm Server’s architecture. Understanding the architecture and capabilities of the dm Server allows us to explore the different approaches we can take to architecting our applications. Our code is no longer bound by the monolithic structure of WARs, RARs, EJB JARs and similar foul beasts. However, we cannot ignore existing applications and we dedicate two chapters to moving existing Java enterprise applications to the dm Server. Finally, we show how to monitor and manage dm Server instances in production environment and — using the information we gathered — we explain how to improve your applications’ performance and reliability.

Wait no longer!

If you are interested in writing new OSGi-based applications or migrating existing Java enterprise applications to the dm Server, wait no longer and get your hands on our book at http://www.manning.com/machacek/.

dm Server Migration Episode IV

October 22nd, 2008

We have just contributed our own videocast to the YouTube black hole. It is the first out of three videos that deal with migrating Java EE applications to the dm Server.
This first part (for some strange reason, we decided to call it Episode IV) shows the outline of the process, but skims over the details such as the structure of the archives being deployed and the MANIFEST.MF descriptors.
The second part is going to concentrate on packaging structure of the shared libraries WAR deployment model. The second part is therefore going to show details of the Ant build files. We are also going to show the Bnd tool that bundlifies any JAR.
The final part is going to show the shared services WAR model; we are going to show the main reason why you’d move to the shared services WAR: to use services exported from other bundles in the dm Server!

Episode IV

And the winner is…

October 16th, 2008

We’ve received the cover designs for our book, dm Server in Action. We had three choices and the final scores are:
In the third place miserable looking so and so, whose pen hides Ani’s name!

In the second place, a fairly wealthy turk. We think he’s rich, because he’s dressed in blue and in his time, blue was the most expensive colour. To get truly rich blue colour, you needed natural ultramarine, which turns out to be the most difficult pigment to grind by hand, and for all except the highest quality of mineral sheer grinding and washing produces only a pale grayish blue powder.

And the winner is…

We actually don’t know anything about her, we can only guess that she’s Dutch and that she’s not particularly wealthy. But that’s OK, we’re not snobs at all, even if we live in the UK, have kippers and toast for breakfast and cups of tea and biscuits at 5.

jQuery Presentation at the Spring User Group in London

October 14th, 2008

Here is the presentation I gave on jQuery at the Spring User Group in London.

Q&A session for the whole event is at the end.

Some people attended the Spring event because of the jQuery talk. Bonus!!