org.norther.tammi.core.thread
Class DefaultScheduler

java.lang.Object
  extended by org.norther.tammi.core.base.Adaptee
      extended by org.norther.tammi.core.thread.DefaultScheduler
All Implemented Interfaces:
Serializable, EventListener, NotificationBroadcaster, NotificationEmitter, NotificationListener, ScheduledTimer, Manageable, MBeanDelegate, Startable, Scheduler
Direct Known Subclasses:
DefaultTimeout

public class DefaultScheduler
extends Adaptee
implements Scheduler, NotificationListener

A default implementation of Scheduler.

Author:
Ilkka Priha
See Also:
Serialized Form

Field Summary
 
Fields inherited from class org.norther.tammi.core.base.Adaptee
ADAPTEE_NOTIF_DESCRIPTION, ADAPTEE_NOTIFICATIONS
 
Fields inherited from interface org.norther.tammi.core.base.MBeanDelegate
ARRAY_TYPE, OBJECT_TYPE, PRIMITIVE_TYPE, STRING_TYPE
 
Constructor Summary
DefaultScheduler()
          Constructs a new scheduler.
 
Method Summary
 Future executeAfterDelay(Callable command, long delay)
          Excecutes the given callable command after waiting for the given delay.
 Future executeAfterDelay(Runnable command, long delay)
          Excecutes the given command after waiting for the given delay.
 Future executeAt(Callable command, Date date)
          Executes the given callable command at the given time.
 Future executeAt(Runnable command, Date date)
          Executes the given command at the given time.
 Future executePeriodically(Runnable command, Date date, long period)
          Executes the given command every period milliseconds starting at the given time.
 Future executePeriodically(Runnable command, long period, boolean startNow)
          Executes the given command every period milliseconds.
 Future executePeriodically(Runnable command, long delay, long period)
          Executes the given command every period milliseconds after waiting for the given delay.
protected  Executor getExecutor()
          Gets the referent of the executor MBean.
 ObjectName getExecutorName()
          Gets the the executor of this scheduler.
 Runnable getIdleCommand()
          Gets the idle command.
 long getIdleDelay()
          Gets the idle delay.
 ObjectName getThreadFactoryName()
          Gets the thread factory of this scheduler.
protected  TimerDaemon getTimer()
          Gets the implementation of the timer.
 void handleNotification(Notification notif, Object handback)
          Handles notifications from the embedded thread factory.
 boolean isIdleSupported()
          Checks whether idle commands are supported by this timer.
 boolean isStarted()
          Checks whether the startable has been started.
 void postmanaged()
          This method is called when the implementing adaptee has been managed either during post-registration of the corresponding adapter MBean or just after it is explicitly added to the adapter MBean during run-time.
 void setExecutorName(ObjectName executor)
          Sets the executor of this scheduler.
 void setIdleCommand(Runnable command)
          Sets the idle command.
 void setIdleDelay(long delay)
          Sets the idle delay.
 void setThreadFactoryName(ObjectName factory)
          Sets the thread factory of this scheduler.
 void start()
          Starts (or restarts) a thread to process commands, or wake up an existing thread if one is already running.
 void stop()
          Cancels all tasks and interrupts the background thread executing the current task, if any.
 void unmanaged()
          This method is called when the implementing adaptee is unmanaged either during pre-deregistration of the corresponding adapter MBean or just before it is explicitly removed from the adapter MBean during run-time.
 
Methods inherited from class org.norther.tammi.core.base.Adaptee
addAdaptee, addNotificationListener, getAttributeSupport, getBroker, getCanonicalName, getDomain, getFactory, getLoader, getLog, getLog, getMBean, getMBeanServer, getNotificationInfo, getObjectName, getRegistrationTime, getSequenceNumber, hasListeners, isRegistered, premanaged, removeNotificationListener, removeNotificationListener, sendNotification, sendNotification, sendNotification, sendNotification, unregister
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

DefaultScheduler

public DefaultScheduler()
Constructs a new scheduler.

Method Detail

postmanaged

public void postmanaged()
Description copied from interface: Manageable
This method is called when the implementing adaptee has been managed either during post-registration of the corresponding adapter MBean or just after it is explicitly added to the adapter MBean during run-time.

Specified by:
postmanaged in interface Manageable
Overrides:
postmanaged in class Adaptee

unmanaged

public void unmanaged()
               throws Exception
Description copied from interface: Manageable
This method is called when the implementing adaptee is unmanaged either during pre-deregistration of the corresponding adapter MBean or just before it is explicitly removed from the adapter MBean during run-time.

Specified by:
unmanaged in interface Manageable
Overrides:
unmanaged in class Adaptee
Throws:
Exception - if the adaptee refused to be unmanaged.

getThreadFactoryName

public ObjectName getThreadFactoryName()
Description copied from interface: Scheduler
Gets the thread factory of this scheduler.

Specified by:
getThreadFactoryName in interface Scheduler
Returns:
the name of the factory or a query.

setThreadFactoryName

public void setThreadFactoryName(ObjectName factory)
Description copied from interface: Scheduler
Sets the thread factory of this scheduler.

Specified by:
setThreadFactoryName in interface Scheduler
Parameters:
factory - the name of the factory or a query.

getExecutorName

public ObjectName getExecutorName()
Description copied from interface: Scheduler
Gets the the executor of this scheduler.

Specified by:
getExecutorName in interface Scheduler
Returns:
the object name of the executor or a query.

setExecutorName

public void setExecutorName(ObjectName executor)
Description copied from interface: Scheduler
Sets the executor of this scheduler. If it is not set, the default one will be used.

Specified by:
setExecutorName in interface Scheduler
Parameters:
executor - the object name of the executor or a query.

executeAt

public Future executeAt(Runnable command,
                        Date date)
Description copied from interface: ScheduledTimer
Executes the given command at the given time.

Specified by:
executeAt in interface ScheduledTimer
Parameters:
command - the command to run at the given time.
date - the absolute time to run the command.
Returns:
a cancellable task.

executeAfterDelay

public Future executeAfterDelay(Runnable command,
                                long delay)
Description copied from interface: ScheduledTimer
Excecutes the given command after waiting for the given delay.

Sample Usage. You can use a ClockDaemon to arrange timeout callbacks to break out of stuck IO. For example (code sketch):

 class X
 {
     ...
     ScheduledTimer timer = ...
     Thread readerThread;
     FileInputStream datafile;
  
     void startReadThread()
     {
         datafile = new FileInputStream("data", ...);
         readerThread = new Thread(new Runnable()
         {
             public void run()
             {
                 for(;;)
                 {
                     // Try to gracefully exit before blocking.
                     if (Thread.currentThread().isInterrupted())
                     {
                         quietlyWrapUpAndReturn();
                     }
                     else
                     {
                         try
                         {
                             int c = datafile.read();
                             if (c == -1)
                             {
                                 break;
                             }
                             else
                             {
                                 process(c);
                             }
                         }
                         catch (IOException x)
                         {
                             cleanup();
                             return;
                         }
                     }
                 }
             }
         };
         readerThread.start();
         // Establish callback to cancel after 60 seconds.
         timer.executeAfterDelay(new Runnable()
         {
             public void run()
             {
                 readerThread.interrupt();  // try to interrupt thread
                 datafile.close();  // force thread to lose its input file
             }
         }, 60000);
     }
 }
 

Specified by:
executeAfterDelay in interface ScheduledTimer
Parameters:
command - the command to run after the delay.
delay - the delay from now to run the command in msecs.
Returns:
a cancellable task.

executePeriodically

public Future executePeriodically(Runnable command,
                                  long period,
                                  boolean startNow)
Description copied from interface: ScheduledTimer
Executes the given command every period milliseconds. If startNow is true, execution begins immediately, otherwise, it begins after the first period delay.

Sample Usage . Here is one way to update Swing components acting as progress indicators for long-running actions.

 class X
 {
     JLabel statusLabel = ...;
     int percentComplete = 0;
     synchronized int  getPercentComplete() { return percentComplete; }
     synchronized void setPercentComplete(int p) { percentComplete = p; }
  
     ScheduledTimer timer = ...;
     void startWorking()
     {
         Runnable showPct = new Runnable()
         {
             public void run()
             {
                 SwingUtilities.invokeLater(new Runnable()
                 {
                     public void run()
                     {
                         statusLabel.
                             setText(getPercentComplete() + "%");
                     }
                 }
             }
         };
  
         final Future updater = timer.executePeriodically(showPct, 500, true);
         Runnable action = new Runnable()
         {
             public void run()
             {
                 for (int i = 0; i < 100; ++i)
                 {
                     work();
                     setPercentComplete(i);
                 }
                 updater.cancel();
             }
         };
  
         new Thread(action).start();
     }
 }
 

Specified by:
executePeriodically in interface ScheduledTimer
Parameters:
command - the command to run at each cycle.
period - the period, in msecs. Periods are measured from start-of-task to the next start-of-task. It is generally a bad idea to use a period that is shorter than the expected task duration.
startNow - true if the cycle should start with execution of the task now. Otherwise, the cycle starts with a delay of period milliseconds.
Returns:
a cancellable task.

executePeriodically

public Future executePeriodically(Runnable command,
                                  Date date,
                                  long period)
Description copied from interface: ScheduledTimer
Executes the given command every period milliseconds starting at the given time.

Specified by:
executePeriodically in interface ScheduledTimer
Parameters:
command - the runnable to execute.
date - the startnig date.
period - the period.
Returns:
a cancellable task.

executePeriodically

public Future executePeriodically(Runnable command,
                                  long delay,
                                  long period)
Description copied from interface: ScheduledTimer
Executes the given command every period milliseconds after waiting for the given delay.

Specified by:
executePeriodically in interface ScheduledTimer
Parameters:
command - the runnable to execute.
delay - the delay in msecs.
period - the period.
Returns:
a cancellable task.

executeAt

public Future executeAt(Callable command,
                        Date date)
Description copied from interface: ScheduledTimer
Executes the given callable command at the given time.

Specified by:
executeAt in interface ScheduledTimer
Parameters:
command - the command to run at the given time.
date - the absolute time to run the command.
Returns:
a cancellable task.

executeAfterDelay

public Future executeAfterDelay(Callable command,
                                long delay)
Description copied from interface: ScheduledTimer
Excecutes the given callable command after waiting for the given delay.

Specified by:
executeAfterDelay in interface ScheduledTimer
Parameters:
command - the command to run after the delay.
delay - the delay from now to run the command in msecs.
Returns:
a cancellable task.

isIdleSupported

public boolean isIdleSupported()
Description copied from interface: ScheduledTimer
Checks whether idle commands are supported by this timer.

Specified by:
isIdleSupported in interface ScheduledTimer
Returns:
true if idle is supported, false otherwise.

getIdleCommand

public Runnable getIdleCommand()
Description copied from interface: ScheduledTimer
Gets the idle command.

Specified by:
getIdleCommand in interface ScheduledTimer
Returns:
the idle command or null.

setIdleCommand

public void setIdleCommand(Runnable command)
Description copied from interface: ScheduledTimer
Sets the idle command.

Specified by:
setIdleCommand in interface ScheduledTimer
Parameters:
command - the idle command.

getIdleDelay

public long getIdleDelay()
Description copied from interface: ScheduledTimer
Gets the idle delay.

Specified by:
getIdleDelay in interface ScheduledTimer
Returns:
the idle delay in msecs.

setIdleDelay

public void setIdleDelay(long delay)
Description copied from interface: ScheduledTimer
Sets the idle delay.

Specified by:
setIdleDelay in interface ScheduledTimer
Parameters:
delay - the idle delay in msecs.

isStarted

public boolean isStarted()
Description copied from interface: Startable
Checks whether the startable has been started.

Specified by:
isStarted in interface Startable
Returns:
true if started, otherwise false.

start

public void start()
           throws Exception
Description copied from interface: ScheduledTimer
Starts (or restarts) a thread to process commands, or wake up an existing thread if one is already running. This method can be invoked if the background thread crashed due to an unrecoverable exception in an executed command.

Specified by:
start in interface ScheduledTimer
Specified by:
start in interface Startable
Throws:
Exception - if starts fails.

stop

public void stop()
Description copied from interface: ScheduledTimer
Cancels all tasks and interrupts the background thread executing the current task, if any. A new background thread will be started if new execution requests are encountered. If the currently executing task does not repsond to interrupts, the current thread may persist, even if a new thread is started via restart().

Specified by:
stop in interface ScheduledTimer
Specified by:
stop in interface Startable

handleNotification

public void handleNotification(Notification notif,
                               Object handback)
Handles notifications from the embedded thread factory.

Specified by:
handleNotification in interface NotificationListener
Parameters:
notif - the notification.
handback - not used.

getExecutor

protected Executor getExecutor()
Gets the referent of the executor MBean.

Returns:
the referent of the executor MBean.
Throws:
IllegalStateException - if not available.

getTimer

protected TimerDaemon getTimer()
Gets the implementation of the timer.

Returns:
the timer.
Throws:
NullPointerException - for missing resources.
IllegalStateException - if not registered or started.


Copyright © 2004 The Norther Organization. All rights reserved.