Java example of GenericService methods

The example uses a static Boolean instance variable, _run, to indicate when the service should cease running. There is also a java.lang.Object that is used as a semaphore to allow synchronization among multiple threads. The start() method sets the _run variable to true; start() must also perform any other necessary initialization that are needed by your service, such as opening files, database connections, and so forth. run() executes a while loop as long as the _run variable is true. In each loop iteration, run() performs some of the work that the service is responsible for, such as refreshing a copy of a remote database table, then calls the Object.wait() method to relinquish the CPU. The stop() method sets the _run variable to false and calls the Object.notifyAll() method on the semaphore, causing the run() method to return. Before returning, run() cleans up resources that were allocated in the start() method.

public class MyService
{
public static boolean _run;
public static Object _lock = new Object();

public void start()
{
    _run = true;
    ... perform necessary initializations ...
}

public void run()
{
    while (_run)
    {
        try
        {
            ... do whatever this service does 
                on each iteration, then go back
                to sleep for a while ...
            synchronized(_lock) 
            {
                _lock.wait(100000);
            }
        }
        catch (InterruptedException ie)
        {
            _run = false;
        }
    }
    ... perform necessary cleanup and deallocations ...

}

public void stop()
{
    _run = false;
    // Wake up any instances that are waiting on the mutex
    synchronized (_lock) 
    {
        _lock.notifyAll();
    }
}
}