« June 2008 | Main | August 2008 »

July 2008

Jul 27, 2008

Static Members in Inner Classes? The Answer

I asked a question a few days ago, regarding static members in inner classes. I presented an example with two static members, one was integer the other Object type, the integer compiled correctly and the Object did not. Here's how it looks like in the IDE:

Java Riddle

The answer is found in the Java Language Specification 3rd Edition, Section 8.1.3:

Inner classes may not declare static members, unless they are compile-time constant fields

That's the answer. The integer is a compile-time constant which is in-lined by the compiler. The Object is not. Here are some more examples:

Java-riddle-3

By the way, if the class was a static nested class, rather than an inner-class, there wouldn't be any problem defining static members. Plus, constants are inherited when using extensions. This means that the following is legit:

Java-riddle-4


IMHO, Java is not a complex language. It is much simpler than C++, for sure. However, it does have some odd edges.

Jul 24, 2008

Asking Knowledge Questions during Job Interviews

I posted a riddle in Java yesterday that showed two examples of Static members in an Inner-class, one compiled correctly, the other not. You can check out the answer in the comments. I also wrote in the post that this is "guaranteed to make people mumble in job interviews". Several readers complained that this would make a terrible job interview question. I beg to differ.

For starters, one should remember that a job interview is not a test. In most standard written tests, the goal is to provide the correct answer. Each correct answer is worth some points. The more you answer correctly, the higher your score. Tests are good tools for assessing knowledge and, to some degree, intelligence. 

In a job interview, it's different. The goal is to asses the candidate and form an impression. Asking questions and grading the correctness of the answer is important, but it's not the main issue. It's not just getting to the target, it's how you get there (or not). In the interview, you want to detect other factors like: personality, communication skills, creativity, positive thinking and resourcefulness. I found myself more than once approving people who fail to solve a question and disqualifying people who answered correctly.

I gathered just a few examples of what a candidate might do with the question I presented and how you may proceed and interpret the behavior (the next section is written in male form for convenience).

The candidate is puzzled and has no idea

Ask the candidate what he would do next in a real situation. If he does not know that's a bad sign of somebody who would come running to you on every problem. Problem solving skills are one of the main characteristics of a good developer.

He wants to search the web

Let him, but only if he asks. This shows creativity and thinking outside the box: I can search Google during my interview. Knowing how to find answers over the web is an important skill. Many of the experienced developers are so good at it that they take it for granted. Don't just give him time to search the web. Do it with him. See how he works in real situations. Is he cleaver enough to search for the right terms and sift through the search results? This is where intelligence and experience comes into play.

The candidate may offer some wrong answers

Listen carefully and interact. Engage in a discussion. You'll get a good idea on how intimately he knows Java. He may give an explanation which contradicts the basics of the language and demonstrate complete misunderstanding of the concepts. The purpose is to test understanding and experience not memorizing the spec.

The candidate protests about the question

That is an acceptable reaction, I would expect that from "hot shots". There comes a time in a developers' job where he will be asked to do things which he may not like. That will give you some idea of how he's going to react in that situation. 

The candidate decides that it's not an acceptable question and refuses to answer

It may indicate that the candidate has an inflated ego, as he feels this question does not dignify an answer. I'm not saying he won't make a good developer, but it would tell you something about his abilities as a team player.  

I tried to think of some possible scenario, clearly, there are many others. My point is that this may be a legitimate job interview question, and not because it checks the candidate ability to memorize a spec, but because it may provide new insights regarding the candidate, insights which may be different from those you would get from the other questions you'd normally use.

Jul 23, 2008

Java Riddle: Static Members in Inner Classes?

Here's something that can annoy the most experienced Java developers and is guaranteed to make people to mumble in job interviews (if that's your thing).


Consider the following piece of code:


Java Riddle

On the face of it, the two variables are identical, but of a different type. So what's the problem here? 

Hint 1: This will work with a String. It will not work with an int array.

Hint 2:  This is the error you'll be getting (at least in Eclipse):

The field OBJECT_CONST cannot be declared static; static fields can only be declared in static or top level types

This hint is only more confusing. The error seems to apply to the integer field as well. So, what's the deal here?

If you know the answer, leave a comment. 

Updated: Check out the answer here.

Jul 22, 2008

Eclipse: Gracefully Loading a Heavy Plugin

Here's the challenge: I have a plug-in which may take more than a few seconds to load. That's not a problem if the plug-in is loaded when the platform starts since the user waits for platform to load anyway. However, if the plug-in is loaded on-demand, after the platform is already started, the user may experience an unexplained freeze. 

To overcome this behavior, it is best to use some progress dialog with a monitor when starting your plugin. This is simple, however, the less-than-trivial question is: how to determine if the platform is starting?  

Those with some knowledge of Eclipse would simply direct me to a very simple API call:

PlatformUI.isWorkbenchRunning()

One major disadvantage.. this is useless, since it will return true when the platform is still loading as well. It is considered running at this point.

Searching in the Eclipse newsgroups portal, I came across another idea:

Bundle b = Platform.getBundle("org.eclipse.swt");
if (b==null || b.getState() != Bundle.ACTIVE) {
   System.out.println("no UI...");
}

This doesn't work, since SWT is already resolved when the splash screen is shown. You can test other bundles, if you'd like, but I find it hard to believe you'll discover any well-defined and consistent difference between the two situations: loading upon launch and loading after it is complete.

My next idea was to check the visibility of the default shell. Nope, it is considered visible at startup. I tried checking for the existence of workbench visual parts and, guess what, they're already there in both cases. After some trial and error I found a very simple way of doing that. One of the distinct features when the splash screen is showing is that you don't see a menu-bar. From that I derived the following test:

Display.getCurrent().getActiveShell().getMenuBar() == null

This will return true when the platform is still launching and a splash screen is shown. Putting it all together and adding all the null checks I could think of, I wrote the following method for checking if the shell is already open and return it if it is:

private Shell findStartedShell() {
   Shell result = null;
   final Display currentDisplay = Display.getCurrent();
   if (currentDisplay != null) {
      result = currentDisplay.getActiveShell();
      if ((result != null) && (result.getMenuBar() == null)) {
         result = null;
      }
   }
   return result;
}

I used a ProgressMonitorDialog to show the progress and an IRunnableWithProgress to implement the lengthy startup process. Eventually, the plugin Activator start method would look like this:

public void start(final BundleContext context) throws Exception {
   super.start(context);
   plugin = this;
   final IRunnableWithProgress statupOperation = 
      new IRunnableWithProgress() {

      public void run(final IProgressMonitor monitor) throws
         InvocationTargetException, InterruptedException {
         // do your initialization here
         // use the monitor to set the task name 
         // and report progress

      }
   };

   final Shell activeShell = findStartedShell();
   if (activeShell != null) {
      final ProgressMonitorDialog progressMonitorDialog =
         new ProgressMonitorDialog(activeShell);
      progressMonitorDialog.run(false, false, statupOperation);
   } else {
      statupOperation.run(new NullProgressMonitor());
   }
}

The above will do exactly what we were looking for: if the platform is launching, it will proceed with normal startup (the splash screen shows the progress of loading all the plugins) and, if the platform is already loaded, it will show a progress dialog.

Found a better way of doing that?  Let me know in the comments.

Jul 08, 2008

JProfiler: Your Java code could be running faster in under two hours

A couple of weeks ago I found myself in a position which is well known to any professional Java developer: my software was simply too slow. After tackling some obvious pain-points, I had to turn to help of a profiler. At the end of the day, I managed to cut the execution time of some processes by 50% and more, by using JProfiler form ej-technologies

The Open Source Alternatives 
As an Eclipse user and a strong OSS supporter, I first started searching for the open source alternatives. In the past, I have used the Eclipse Test & Performance Tools Platform, aka TPTP. However, TPTP is no longer an option for me since it does not support Mac OS X. TPTP is a good, solid, tool but it is not a simple one to install and use. Just to be clear: a simple tool would be a tool I can install and use without reading a manual. TPTP comes with a complex setup process.

I searched for some other free tools. I found this list of open source Java profilers and wasted about 3-4 hours running through it. None of them worked well. Most of them were buggy, some eventually worked but did not produce enough information or produced too much information, which is just as bad. Most of the tools are focused on memory analysis, while I needed execution time analysis. I had to look elsewhere.

My Experience with JProfiler
I'll start from the bottom line. JProfiler is not the prettiest tool you can find. Its' integration with Eclipse leaves much to be desired. However, it has many advantages:

  • Very simple to use, compared to tools in its' class.
  • Provides all the information you will desire with extensive views and predefined filters to make sure you'll get just the information you need.
  • Relatively low execution overhead with many profiling options (instrumentation, sampling, etc.) and highly configurable settings.
  • It displays the information while the program is running, as opposed to other tools I've used, where you have to stop the analysis to get some results. 

I downloaded JProfiler and installed it using the provided installer. Like other profilers, JProfiler integrates with the IDE, supporting Eclipse and IntelliJ. In Eclipse, you use the "Profile" command, which uses the same "Launch Configurations" as the "Run" and "Debug" commands. At this point, you'll be transferred to JProfiler to start the profiling session. It took me less than half an hour to start profiling (including the download and installation), without any prior knowledge of the product and without reading any documentation. It took me another half an hour to explore all the views and understand where I can start cutting execution time. About half an hour later, I was running much faster. As I wrote earlier, about 50% faster with a couple more fixes I did that day.

Since then, I had a chance to use JProfiler on a number of occasions and it just works: profile, find the problem, fix and retest. I don't need any special preparation or setup: I just launch JProfiler using my existing launch configuration and a couple of minutes later I have the results. I even tried it on Windows, as well and it works exactly the same. You don't need to buy an additional license for that: you can remotely profile your application across the supported platforms (Windows, Mac, Linux, Solaris, AIX and HP-UX) without running JProfiler on the remote machine.

JProfiler in Action
I'm not an expert user and my experience with JProfiler is limited. I took a few screenshots to show how simple yet powerful is JProfiler. The first screen is the Session Startup, which is the first dialog you get when you launch a new profiling session.

JProfiler Session Startup

What I like most about this window is the two lower bars that give you an estimate on how intensive this profiling session is going to be in terms of memory and CPU usage. If you change any of the profiling parameters, these bars will reflect the change. Going into the profile settings, you get an assortment of configuration options:

JProfiler Profile Settings

You can choose from predefined settings or use a custom settings. Once you select an option you'll see some explanation in the dialog itself, so there's no need to start looking for documentation. Once you get the hang of it, you can start exploring the custom options, but I found the predefined settings totally sufficient for my needs.

My focus was on execution time of a simple Java program, so the default option worked best for me. When analyzing my execution time, the most helpful tool was the "Hot Spots" view:

JProfiler HotSpots

In this view, the most expensive calls are sorted in a descending order. You can expand the call and see which methods invoked it and, for each of those methods, what was its' share in the overall performance cost. This graph is updated every 5 seconds while the program executes. 

You may also choose to see it as a call graph:

JProfiler Call Graph

In this graph, each method gets a color according to its' contribution to the overall performance. The more expensive the call, the darker it will be. For each method you can expand the callers and methods being invoked. This makes it a good tool for identifying the critical path. All of these views can be exported to a readable HTML format, including the graphs.

Summary
It is my opinion that every professional developer should know how to profile code. I don't believe profiling is an art which should be left to dedicated performance teams (my former employer took that approach), mostly because it is the combination of knowing the code and mastering the profiling technique which yields the best results. In an ideal situation, every developer should have a profiler in his or her arsenal, ready to be launched at any given time.

Should you buy a profiler?  Even if TPTP works on your platform, it is still behind the commercial tools. It seems that profilers are one of the few segments in the development tools market, where open source tools are not catching up with their commercial counterparts. It is more of a question of how you value your time. You can read my related post of the subject from one year ago: When saving a buck actually costs you more. JProfiler will simply provide the results faster.

About nWire

  • nWire Logo
    Browse & visualize all code association in one extremely powerful view, quick search for methods, fields and more. Boost your coding productivity in Eclipse™.
    Watch a 4 minute demo that will change the way you look at your code.
    Visit nwiresoftware.com

Twitter Updates

    follow me on Twitter
    My Photo

    My Other Accounts

    Delicious Digg Facebook FriendFeed Google Talk LinkedIn Reddit Twitter

    AddThis Social Bookmark Button
    Blog powered by TypePad
    Member since 05/2007