JThreadKit Home

SizeMonitored Demo - Instructions

Overview

The SizeMonitored interface is widely used throughout JThreadKit. It is used to keep tabs on the current "size" of something--for example the number of elements in a List. The List interface from the Collections API already has a size() method that returns the number of elements stored in the list. But if the list is also SizeMonitored we can have one thread call waitUntilEmpty() (a method on the SizeMonitored interface), while another thread removes elements from the list. There's an interface defined in the com.jthreadkit.collection package that is a combination of the List interface and the SizeMonitored interface and it's called: SizeMonitoredList (and it's one of the options in this demo). Throughout JThreadKit, there are many other classes that implement and interfaces that extend the SizeMonitored interface.

Running the Demo

Once the demo has been launched, start it by first choosing a SizeMonitored Type, and then click "Start". Details about the demo are displayed in the Results text area. The demo highlights the following features of a SizeMonitored object:

  • Size Change Notification

    After constructing the SizeMonitored Object, a SizeChangeListener is added to it. Each time the size of the SizeMonitored changes, the SizeChangeListener's sizeChanged(SizeMonitored sm, int newSize) method is called. This method is called by the thread that just changed the value--while calling this method, this thread continues to hold the exclusive lock on the Object returned by the getLockObject() method on SizeMonitored. In light of this, implementations of this method should do their work quickly (and without making method calls that potentially block!). In addition, if the size is altered again as a result of something done during this method call, re-notification will not occur.

    The left portion of the demo display contains the Listener text area. Each time sizeChanged() is called, the new size is appended to this text area.

  • Inter-Thread Communication

    In the demo, two threads are interacting with the same SizeMonitored Object. The first thread creates the SizeMonitored Object. The second thread calls the waitForSizeToClimbTo(int atLeast) method which causes it to block, waiting until the size is equal to the target value of 5. Once the first thread adds five objects (Strings are used in the demo), the second thread begins removing them.