Core Java Books

Tuesday, 5 April 2011

Java GUI Application Shutdown Gotcha

In recent times I've had issues with one or two Java GUI application not shutting down when I close them. They seem to stay around as a process, consuming computer resources. Today I got to the bottom of the problem and it's a bit of a nasty gotcha which I wasn't aware of before so I thought I would share it.

In theory when you close a Java application all the threads should be stopped and the process should die. Im my case when I monitored the application the threads I expected to finish such as Swing worker pools were still alive, Strange. The reason turned out to be that the AWT Shutdown thread wasn't terminating all the helper threads, and the reason for this was that there were still AWT Events in the EventQueues. The reason for this is a real sneaky little gatcha, I will explain.

My application used a Thread which had a regular sleep but when woke up would so some calculation and then make a call to update the gui:

Thread updateThread = new Thread(new Runnable() {

  @Override
  public void run() {
    int i = 0;
    do {
      try {
        Thread.sleep(300); // 300ms
        gui.updateValue(SOME_VALUE);
      } catch (InterruptException ex) {
        return;
      }
      frame.setValue(SOMEDATA);
    } while (i++ < 100);
  }


}, "updateThread");

updateThread.setDaemon(true);
updateThread.start();

Now you will notice that the thread returns if it is interrupted and also it is started as a Daemon thread. I had thought that as part of the application shutdown the thread would be terminated but NO it wasn't. This was caused by gui.updateValue(SOME_VALUE) making use of InvokeLater:



  public void updateValue(final int value) {

        // make sure we access graphics in the EDT thread
        java.awt.EventQueue.invokeLater(new Runnable() {

          @Override
            public void run() {
                try {
                     ...
                     ...
                     ...
                    SOME CODE
                } catch (Exception t) {
                    // not a lot to do
                }
            }
        });
    }

The InvokeLater is basically putting an event on the EventQueue and because of this the AWT Shutdown thread want shutdown the application. The AWT Shutdown thread checks the EventQueues every seconds but as you will see my Thread does an update subsecond (300ms) so there is always an event on the Queue! So in short the AWT Shutdown thread never terminates the threads I want it to terminate and so the application needs to be killed.

The work around is simple in the while loop of my thread I also check that the JComonent that is to be updated via it is still visible and shown, if it is not the loop is exited, the thread dies and so there are no more events put on the Event thread and whooohooo the application closes as expected :)


Thread updateThread = new Thread(new Runnable() {

  @Override
  public void run() {
    int i = 0;
    do {
      try {
        Thread.sleep(300); // 300ms
        gui.updateValue(SOME_VALUE);
      } catch (InterruptException ex) {
        return;
      }
      frame.setValue(SOMEDATA);
    }while (i < 100 && progressGlassPane.isVisible() && progressGlassPane.isShowing());
  }
}, "updateThread");
updateThread.setDaemon(true);
updateThread.start();


So in short don't call InvokeLater from a helper thread at sub-second frequency unless you also terminate the thread if the component it is updating is no longer visible!
 
As a side note after I spotted the issue I found this very useful article on the same subject which highlighted the same issue I was having.

Monday, 28 March 2011

Providing Mock API's at Runtime

This article is about how I provide a mock api's to my applications at runtime so I can test them without external services being involved.

Many of the application I work on make use of api's to servers, communications engines and so on. I find it useful to be able to test my application with mock API's so I have more control of the tests on it and can test it standalone. Also the mechanism provided allows me to run my application when a service has yet to be delivered but is defined. I could make use of dependency injection if I was to drag JEE api's into my build but I prefer the simple approach. It might not be perfect but it works.

Lets say I have an external interface that my application makes use of:


public interface Service {
    void addListener(final ServiceListener listener);
    void removeListener(final ServiceListener listener);
}


Now in my application I would typically construct a concrete class either directly  or via a factory method which implements the interface contract. Whilst testing I would like to actually provide another version of the implementing class which can be used to test my application with the interface:


public class MockService implements Service {

    private static List<ServiceListener> listeners = new ArrayList<ServiceListener>();

    public void addListener(ServiceListener listener) {
        listeners.add(listener);
    }

    public void removeListener(ServiceListener listener) {
        listeners.remove(listener);
    }

    public void newRequestReceived(final ExternalRequest request) {
        RequestEvent event = new RequestEvent(request);
        for(ServiceListener listener : listeners) {
            listener.notifyRequestEvent(event);
        }
    }

}

I provide the mock class making use of a command line property:


java -Dservice.api.classname=com.webbyit.MockService -jar myapp.jar



Now in the code of my app I make use of the property (maybe within a factory method) and construct the class provided rather than the default class:


private static Service getService() {
  

    synchronized (ServiceLock) {
        if (Service == null) { 

            String serviceClassName = System.getProperty("service.api.classname");

                if (serviceClassName == null) {
                     Service = new RealService();
                } else {
                    try {
                        Service = (Service) Class.forName(serviceClassName).newInstance();
                    } catch (InstantiationException e) {
                        throwCallServiceInitialisationException(serviceClassName, e);
                    } catch (IllegalAccessException e) {
                        throwCallServiceInitialisationException(serviceClassName, e);
                    } catch (ClassNotFoundException e) {
                        throwCallServiceInitialisationException(serviceClassName, e);
                    }
                }
            }
        }
        return Service;
    } 

}

So what I have done is test for an alternative class being specified by a property (via the command line). If set the code attempts to construct the alternative class and use that instead of the default class usually used by the application.

Monday, 21 March 2011

The Culture of the Locked Stationary Cupboard

This blog is a little bit off topic, it's a short observation of company culture and politics. Specifically this is about the culture of 'The Locked Stationary Cupboard'.

I should start with a little background information. I'm a software consultant, in short I hire out my services to customers and in general develop software for them. This more than often involves working at the customers business premises. Most customers I've dealt with employee 100+ people.

Now when I offer my services to a customer and work on their site I always use my own pens, pencils, calculator ...... however there are times when the pen runs out, the pencil jumps down a black hole and the calculator takes a walk in to the ether. Nothing strange here, all part and parcel of working for yourself. Things get very strange though when you ask a member of staff where the stationary cupboard is though!

I'd always thought of a stationary cupboard as a place where an employee could obtain that most basic of office tools, the pen and pencil. In a well stocked cupboard marker pens, staples, staplers and even rulers were available. All of these items of little monetary value but essential to any office workers tool set. It was in a companies interest to have a well stocked cupboard.

In recent times, and I have noticed this more in larger companies, the stationary cupboard takes on an status similar to that of the 'Ark of the Covenant'. You know it exists, you know you want to find it and open it but by god its not going to be an easy task.

Several obstacles are put in place to stop anyway unwary soul gaining access to the holly of holies. The main obstacle being the BridgeKeeper, you can only pass the bridge and obtain the magical key to the cupboard if you answer all the questions correctly.


  • What do you want.
  • Why do you want it.
  • How many do you want.
  • Has the project manager signed in blood.

Once the key has been obtained and the cupboard door is opened, you feel a sudden chill, the Eye of Sauron. He/She will makes sure that you will NOT take more than you requested. If you are even tempted to take and extra pen, maybe a marker you will never be able to cross the bridge and obtain the golden key again.



So what is it about the stationary cupboard that endows it with such reverence. It seems totally illogical, why would any company employ people, pay them, let them alter code but make it so damn hard to obtain a pen! In many cases developers are allowed to create and alter code that could potentially cause loss of wealth or life if it doesn't function correctly, but a simple request for the keys to the cupboard and they are treated with mistrust.

The crux of the matter I believe is that some companies just have a culture of mistrust. I suspect this is more so in older companies and the Googles of this world are a lot more open minded. Here in the UK we certainly historically come from a culture of 'us and them' with regards to employee and employer relationship. Industry is littered with companies which have gone to the wall because both sides did not trust each other.

My conclusion to this little rant is that any company that has no lock on the stationary cupboard is a forward thinking organisation that is heading in the right direction as regards employee relationships. On the other hand those that protect the jewels within the cupboard should look closely at there internal structure and ask themselves the question, does a pen really warrant all this hassle and mistrust!