xmlBlaster 2.1.0 API

org.xmlBlaster.util
Class TimeoutPooled

java.lang.Object
  extended by java.lang.Thread
      extended by org.xmlBlaster.util.TimeoutPooled
All Implemented Interfaces:
java.lang.Runnable, I_TimeoutManager

public class TimeoutPooled
extends java.lang.Thread
implements I_TimeoutManager

Allows you be called back after a given delay.

Note that this class should be called Timer, but with JDK 1.3 there will be a java.util.Timer.

There is pool of threads used to execute the I_Timeout.timeout() callback. Timer callbacks should complete quickly to not exhaust the pool.

This singleton is thread-safe.

This class does not offer real-time guarantees, but usually notifies you within ~ 20 milliseconds of the scheduled time.

Adding or removing a timer is good performing, also when huge amounts of timers (> 1000) are used.
Feeding of 10000: 10362 adds/sec and all updates came in 942 millis (600MHz Linux PC with Sun JDK 1.3.1) *

Example:

  public class MyClass implements I_Timeout {
    ...
    TimeoutPooled timeout = new TimeoutPooled("TestTimer");
    Timestamp timeoutHandle = timeout.addTimeoutListener(this, 4000L, "myTimeout");
    ...
    public void timeout(Object userData) {
       // userData contains String "myTimeout"
       System.out.println("Timeout happened");
       ...
       // If you want to activate the timer again:
       timeoutHandle = timeout.addTimeoutListener(this, 4000L, "myTimeout");
    }
    ...
    // if you want to refresh the timer:
    timeoutHandle = timeout.refreshTimeoutListener(timeoutHandle, 1500L);
    ...
  }
 
Or a short form:
 TimeoutPooled timeout = new TimeoutPooled("TestTimer");
 
 Timestamp timeoutHandle = timeout.addTimeoutListener(new I_Timeout() {
    public void timeout(Object userData) {
       System.out.println("Timeout happened");
       System.exit(0);
    }
 }, 2000L, null);
 
JDK 1.2 or higher only.

-logging/org.xmlBlaster.util.TimeoutPooled FINER

Author:
xmlBlaster@marcelruff.info
See Also:
TimeoutTest

Nested Class Summary
 
Nested classes/interfaces inherited from class java.lang.Thread
java.lang.Thread.State, java.lang.Thread.UncaughtExceptionHandler
 
Field Summary
private static java.util.logging.Logger log
           
private  java.util.TreeMap<Timestamp,Container> map
          Sorted map
private  boolean mapHasNewEntry
          To avoid sync
private static java.lang.String ME
          Name for logging output
private  boolean ready
          On creation wait until thread started
private  boolean running
          Start/Stop the Timeout manager thread
private  java.util.concurrent.ThreadPoolExecutor threadPool
           
private  boolean useWeakReference
          Hold only weak reference on callback object?
 
Fields inherited from class java.lang.Thread
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY
 
Constructor Summary
TimeoutPooled()
          Create a timer thread with a strong reference on the callback objects.
TimeoutPooled(java.lang.String name)
          Create a timer thread with a strong reference on the callback objects.
TimeoutPooled(java.lang.String name, boolean useWeakReference)
           
TimeoutPooled(java.lang.String name, boolean useWeakReference, java.util.concurrent.ThreadPoolExecutor threadPool)
           
 
Method Summary
 Timestamp addOrRefreshTimeoutListener(I_Timeout listener, long delay, java.lang.Object userData, Timestamp key)
          Checks if key is null -> addTimeoutListener else refreshTimeoutListener() in a thread save way.
 Timestamp addTimeoutListener(I_Timeout listener, long delay, java.lang.Object userData)
          Add a listener which gets informed after 'delay' milliseconds.
 java.lang.String dumpStatus()
           
 long elapsed(Timestamp key)
          How long am i running.
 Container[] getContainers()
           
 int getSize()
          Get number of current used timers.
 long getTimeout(Timestamp key)
          Access the end of life span.
 boolean isExpired(Timestamp key)
          Is this handle expired?

static void main(java.lang.String[] args)
          Method for testing only.
 Timestamp refreshTimeoutListener(Timestamp key, long delay)
          Refresh a listener before the timeout happened.
private  Timestamp refreshTimeoutListener(Timestamp key, long delay, boolean throwExceptionIfMissing)
           
 void removeAll()
          Reset all pending timeouts.
 void removeTimeoutListener(Timestamp key)
          Remove a listener before the timeout happened.
 void run()
          Starts the Timeout manager thread.
 void shutdown()
          Reset and stop the Timeout manager thread.
 long spanToTimeout(Timestamp key)
          How long to my timeout.
(package private) static void testStrongReference()
          Eample for the standard case
(package private) static void testWeakReference()
          Test a weak reference
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Thread
activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, getAllStackTraces, getContextClassLoader, getDefaultUncaughtExceptionHandler, getId, getName, getPriority, getStackTrace, getState, getThreadGroup, getUncaughtExceptionHandler, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setDefaultUncaughtExceptionHandler, setName, setPriority, setUncaughtExceptionHandler, sleep, sleep, start, stop, stop, suspend, yield
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

log

private static java.util.logging.Logger log

ME

private static java.lang.String ME
Name for logging output


map

private java.util.TreeMap<Timestamp,Container> map
Sorted map


running

private boolean running
Start/Stop the Timeout manager thread


ready

private boolean ready
On creation wait until thread started


useWeakReference

private final boolean useWeakReference
Hold only weak reference on callback object?


mapHasNewEntry

private boolean mapHasNewEntry
To avoid sync


threadPool

private final java.util.concurrent.ThreadPoolExecutor threadPool
Constructor Detail

TimeoutPooled

public TimeoutPooled()
Create a timer thread with a strong reference on the callback objects.


TimeoutPooled

public TimeoutPooled(java.lang.String name)
Create a timer thread with a strong reference on the callback objects.

Parameters:
name - The name of the thread

TimeoutPooled

public TimeoutPooled(java.lang.String name,
                     boolean useWeakReference)
Parameters:
name - The name of the thread
useWeakReference - If true the reference on your I_Timeout implementation is only weak referenced and may be garbage collected even that we hold a weak reference.

TimeoutPooled

public TimeoutPooled(java.lang.String name,
                     boolean useWeakReference,
                     java.util.concurrent.ThreadPoolExecutor threadPool)
Method Detail

getSize

public int getSize()
Description copied from interface: I_TimeoutManager
Get number of current used timers.

Specified by:
getSize in interface I_TimeoutManager
Returns:
The number of active timers

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Thread

dumpStatus

public java.lang.String dumpStatus()
Specified by:
dumpStatus in interface I_TimeoutManager

getContainers

public Container[] getContainers()

run

public void run()
Starts the Timeout manager thread.

Specified by:
run in interface java.lang.Runnable
Overrides:
run in class java.lang.Thread

addTimeoutListener

public final Timestamp addTimeoutListener(I_Timeout listener,
                                          long delay,
                                          java.lang.Object userData)
Description copied from interface: I_TimeoutManager
Add a listener which gets informed after 'delay' milliseconds.

After the timeout happened, you are not registered any more. If you want to cycle timeouts, you need to register again.

Specified by:
addTimeoutListener in interface I_TimeoutManager
Parameters:
listener - Your callback handle (you need to implement this interface).
delay - The timeout in milliseconds. You can pass 0L and the Timeout thread will fire immediately, this can be useful to dispatch a task to the timeoutlistener
userData - Some arbitrary data you supply, it will be routed back to you when the timeout occurs through method I_Timeout.timeout().
Returns:
A handle which you can use to unregister with removeTimeoutListener().

refreshTimeoutListener

public final Timestamp refreshTimeoutListener(Timestamp key,
                                              long delay)
                                       throws XmlBlasterException
Description copied from interface: I_TimeoutManager
Refresh a listener before the timeout happened.

NOTE: The returned timeout handle is different from the original one.

NOTE: If you are not sure if the key has elapsed already try this:

 timeout.removeTimeoutListener(timeoutHandle);
 timeoutHandle = timeout.addTimeoutListener(this, "1000L", "UserData");
 

Specified by:
refreshTimeoutListener in interface I_TimeoutManager
Parameters:
key - The timeout handle you received by a previous addTimeoutListener() call.
It is invalid after this call.
delay - The timeout in milliseconds measured from now.
Returns:
A new handle which you can use to unregister with removeTimeoutListener()
Throws:
XmlBlasterException - if key is null or unknown or invalid because timer elapsed already

refreshTimeoutListener

private Timestamp refreshTimeoutListener(Timestamp key,
                                         long delay,
                                         boolean throwExceptionIfMissing)
                                  throws XmlBlasterException
Throws:
XmlBlasterException

addOrRefreshTimeoutListener

public final Timestamp addOrRefreshTimeoutListener(I_Timeout listener,
                                                   long delay,
                                                   java.lang.Object userData,
                                                   Timestamp key)
                                            throws XmlBlasterException
Description copied from interface: I_TimeoutManager
Checks if key is null -> addTimeoutListener else refreshTimeoutListener() in a thread save way.
Note however that your passed key is different from the returned key and you need to synchronize this call to avoid having a stale key (two threads enter this method the same time, the key gets invalid by the first thread and the second passed a stale key as the first thread has not yet returned to update 'key')

Specified by:
addOrRefreshTimeoutListener in interface I_TimeoutManager
Throws:
XmlBlasterException

removeTimeoutListener

public final void removeTimeoutListener(Timestamp key)
Description copied from interface: I_TimeoutManager
Remove a listener before the timeout happened.

Specified by:
removeTimeoutListener in interface I_TimeoutManager
Parameters:
key - The timeout handle you received by a previous addTimeoutListener() call.

isExpired

public final boolean isExpired(Timestamp key)
Description copied from interface: I_TimeoutManager
Is this handle expired?

Specified by:
isExpired in interface I_TimeoutManager
Parameters:
key - The timeout handle you received by a previous addTimeoutListener() call
Returns:
true/false

spanToTimeout

public final long spanToTimeout(Timestamp key)
Description copied from interface: I_TimeoutManager
How long to my timeout.

Specified by:
spanToTimeout in interface I_TimeoutManager
Parameters:
key - The timeout handle you received by a previous addTimeoutListener() call.
Returns:
Milliseconds to timeout, or -1 if not known.

elapsed

public final long elapsed(Timestamp key)
Description copied from interface: I_TimeoutManager
How long am i running.

Specified by:
elapsed in interface I_TimeoutManager
Parameters:
key - The timeout handle you received by a previous addTimeoutListener() call.
Returns:
Milliseconds since creation, or -1 if not known.

getTimeout

public final long getTimeout(Timestamp key)
Description copied from interface: I_TimeoutManager
Access the end of life span.

Specified by:
getTimeout in interface I_TimeoutManager
Parameters:
key - The timeout handle you received by a previous addTimeoutListener() call.
Returns:
Time in milliseconds since midnight, January 1, 1970 UTC or -1 if not known.

removeAll

public final void removeAll()
Description copied from interface: I_TimeoutManager
Reset all pending timeouts.

Specified by:
removeAll in interface I_TimeoutManager

shutdown

public void shutdown()
Description copied from interface: I_TimeoutManager
Reset and stop the Timeout manager thread.

Specified by:
shutdown in interface I_TimeoutManager

main

public static void main(java.lang.String[] args)
                 throws java.lang.Exception
Method for testing only.

Invoke: java -Djava.compiler= org.xmlBlaster.util.TimeoutPooled

Throws:
java.lang.Exception

testStrongReference

static void testStrongReference()
Eample for the standard case


testWeakReference

static void testWeakReference()
Test a weak reference


xmlBlaster 2.1.0 API

Copyright © 1999-2011 The xmlBlaster.org contributers.