Frame Thread

This component will do the memory sampling and place a memory panel update on the event queue. We have derived the frame thread from the Thread class. We also implemented the Runnable interface, so that we can simply start the frame thread by starting an instance. The frame thread will perform the loop that will sample the memory usage and create Swing events. The memory usage is computed from the total memory and the free memory in megabyte units:

            double[] values = new double[1];
            long total = Runtime.getRuntime().totalMemory();
            long free = Runtime.getRuntime().freeMemory();
            values[0] = (double) (total - free) / 1000000;

The little helper class MemoryJob then serves us in submitting an event to the Swing thread. We could also have used an anonymous inner class as a form of a closure. But this anonymous inner class would have forced us to declare some local variables as final. In the end we would have needed a few more local variables. We think the MemoryJob helper class cleaner and more extensible in the future. More details on the helper class can be found in the appendix.

The frame thread has then to sleep a given time. We use the same nano-second approach as found in the headless thread of the previous port sampling example:

            long sleep = SLEEP - (System.nanoTime() - lastTime);
            try {
                while (sleep > 0)
                    sleep = cond.awaitNanos(sleep);
            } catch (InterruptedException x) {
                return;
            }

The frame thread can also be terminated. What is often seen in educational material is the use of a shared flag to control a primary thread by a secondary thread. What we instead expect the secondary thread to do here is a thread.interrupt(). This will terminate the Thread.sleep() with an InterruptedException, eventually only on re-entering the call. We will catch the exception and terminate the loop. This design works as long as the loop does not perform long running non-interruptible calls, which is the case in the present.

Kommentare