Programming Java threads in the real world, Part 5

Has Sun abandoned 'run anywhere'? Plus: Threads and Swing, timers, and getting around stop(), suspend(), and resume() deprecation

1 2 3 4 5 Page 5
Page 5 of 5

    /****************************************************************
    |    Same as await(Alarm.FOREVER)
     **/

106  
107  
108  
    public boolean await(){ return await( FOREVER ); }

    /****************************************************************
    |    Add a listener that will be notified the next time the Alarm goes off. The listeners are notified on a thread that's created just for that purpose, rather than being notified from the timer thread. This way the time spent doing notification dosn't impact the time interval used by the timer. The "action command" in the ActionEvent object will be either the String "stopped" or "expired" (which are also defined in the symbolic constants {@link Alarm.STOPPED} and {@link Alarm.EXPIRED}), depending on whether this notification occured because the timer was stopped manually, or because it expired in the normal way.
     */

109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
  public synchronized void addActionListener(ActionListener l)
    {   observers = AWTEventMulticaster.add(observers, l);
        if( notifier == null )
        {   notifier = new Alarm.Notifier();
            notifier.setDaemon( true );
            notifier.start();
        }
    }

    /****************************************************************
    |    Remove a listener
     */

119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
282  
283  
284  
285  
286  
287  
288  
289  
290  
291  
292  
293  
294  
295  
296  
297  
298  
299  
300  
301  
  public void removeActionListener(ActionListener l)
    {   observers = AWTEventMulticaster.remove(observers, l);
    }
   private class Notifier extends Thread
    {
       public void run()
        {
            ActionListener copy;
           while( observers != null )
            {   synchronized( Alarm.this )
                {   try
                   {   Alarm.this.wait();
                    }
                    catch(InterruptedException e){/*ignore*/}
                   if( (copy = observers) == null)
                       notifier = null;
            }
               if( copy != null )
                   copy.actionPerformed(
                            new ActionEvent(this,0,
                                    is_stopped ? STOPPED : EXPIRED));
            }
            // can't set notifier=null here
        }
    }
    //================================================================
    // Support classes:
    //================================================================
   private final class Clock extends Thread
    {
       private boolean expired             = false;    // continuous timers don't expire
       private boolean notifications_off   = false;
        Clock()
        {   setPriority( getThreadGroup().getMaxPriority() );
        }
       public void run()
        {   
            while( !isInterrupted() )
            {   try
                {   sleep(delay); // release the monitor while sleeping
                    if( isInterrupted() )   // don't notify waiting threads if
                        break;              // we've been stopped by the
                                            // Alarm object.
                   synchronized( this )
                    {   
                        expired = true;
                        if( !notifications_off )
                        {   synchronized( Alarm.this )
                           {   Alarm.this.notifyAll();
                            }
                        }
                        if( type == MULTI_SHOT )
                       {   wait();                     // suspend
                        }
                        else if( type == ONE_SHOT )
                        {
                            // Set the outer-class reference to the
                            // current clock to null so that the
                            // memory can be reclaimed. Note that
                            // we're still synchronized on the outer-
                            // class object.

                            synchronized( Alarm.this)
                            {   if( Alarm.this.clock == this )
                                   Alarm.this.clock = null;
                            }
                            break;
                        }
                    }
                }
                catch(InterruptedException e) // don't notify the waiting
                {   break;                    // threads because an
                }                             // interrupt is used to stop
            }                                 // the timer.
        }
       public void no_notifications()
        {   notifications_off = true;
        }
       public synchronized void restart()
        {   expired = false;
           notify();                       // resume
        }
       public boolean has_expired()                // CONTINUOUS
        {   return (type != CONTINUOUS) && expired; // timers never
        }                                           // expire.
    };
    //================================================================
    // Unit test:
    //================================================================
   static public class Test
    {
       public static void main( String[] args ) throws Exception
        {
            // A recurring timer, runs until it is stoped manually.
            Alarm clock = new Alarm(1000, Alarm.CONTINUOUS );
            clock.start();
            System.out.println("Print time 3 times at 1-second intervals");
            for( int i = 3; --i>= 0; )
            {
                System.out.println( new Date().toString() );
                clock.await( Alarm.FOREVER );
            }
            clock.stop();   // It is essential to stop the timer manually.
                        // Otherwise, the memory for it might never be
                        // reclaimed.
            System.out.println("\nOne-shot:\n");
            // A One-shot. Fire it manually. You don't need to stop()
            // it explicitly---it automatically frees up all threads
            // when it expires.
            clock = new Alarm(1000, Alarm.ONE_SHOT);
            clock.start();
            for( int i = 3; --i>= 0; )
            {
                System.out.println( new Date().toString() + "\r" );
                clock.await( Alarm.FOREVER );
                clock.start();
            }
            System.out.println("\n Multi-shot:\n");
            // A Multi-shot is much like a one-shot. Fire it manually,
            // but you must stop() it explicitly. The main difference
            // is that a MULTI_SHOT timer doesn't recreate the timer
            // thread when it's restarted. The one-shot timer creates
            // the thread anew every time it's started.
            clock = new Alarm(1000, Alarm.MULTI_SHOT);
            clock.start();
            for( int i = 3; --i>= 0; )
            {
                System.out.println( new Date().toString() + "\r" );
                clock.await( Alarm.FOREVER );
                clock.start();
            }
            clock.stop();
            System.out.println( "\n Notifier\n" );
            clock = new Alarm( 1000 );  // 1-second continuous timer
            clock.addActionListener
            (   new ActionListener()
               {   public void actionPerformed( ActionEvent e )
                    {   System.out.println( new Date().toString() 
                                            + e.getActionCommand() );
                    }
                }
            );
            clock.start();
            System.out.println("Sleeping");
            Thread.currentThread().sleep( 5000 );
            System.out.println("Waking");
            clock.stop();
            System.exit(0);
        }
    }
}

Happy trails

Frankly, I'm not completely convinced that all this will indeed work correctly in all situations. I've stared at the code, made diagrams, and analyzed it up the wazoo, but if past experience is any indication, I've probably still missed something. Welcome to the world of thread programming. If you find a flaw in my reasoning (and some of you probably will -- sigh), please send me e-mail.

So that's it for this month. A Timer is a useful thing to have around, not just for animation loops, but for any application that needs to do things at regular intervals or during idle time. Between the new Swing Timer and my own Alarm, all the applications I can think of are covered. The synchronization issues in this code are hairier than usual, but it does serve as a good example of threading in the real world.

Next month, I'll continue with even more threading stuff by delving into implementations of the Observer and Singleton design patterns that work in multithreaded environments. I'll look at the inner workings of the AWTEventMulticaster class and other ways of sending notifications efficiently in a thread-safe way. I'll also look at how to create a Singleton efficiently, and how to work around a 1.1 VM bug that makes it difficult to produce Singletons.

Learn more about this topic

Related:
1 2 3 4 5 Page 5
Page 5 of 5