Search code examples
javaderbyjavadb

Kill Derby DB Network Server on background


I'm looking for a good way to run a Apache Derby server in network mode. I'm using the NetworkServerControl to start the server and it's working great.

I start the server like this:

/**
 * starts the network server
 * @return true if sucessfull
 */
public boolean start()
{
    try
    {
        // just to be sure that we don't start two servers
        this.stop();

        server = new NetworkServerControl();
        server.start( null );

        return true;
    }
    catch ( Exception ex )
    {
        this.logLogger.debug( ex );
        return false;
    }
}

And stop it like this:

/**
 * stops the server
 * 
 * @return true if there were no problems stopping the server
 */
public boolean stop()
{
    try
    {
        if ( server == null )
        {
            server = new NetworkServerControl();
        }
        server.shutdown();

        return true;
    }
    catch ( Exception ex )
    {
        this.logLogger.debug( ex );
        return false;
    }
}

On the main() I have this so the process doesn't die while the server is running

(...)
clsDB.start();

while( clsDB.testForConnection() )
{
   Thread.sleep( 60000 );
}

testForConnection() looks like this:

/**
 * Try to test for a connection
 * 
 * @return true if the server is alive
 */
public boolean testForConnection()
{
    try
    {
        server.ping();

        return true;
    }
    catch ( Exception ex )
    {
        this.logLogger.debug( ex );
        return false;
    }
}

My problem is that when a new instace of my JAR is called the old one will still be running (unless I'm really really lucky and the test is made before the new server is started).

I know I could just test if the server is already running and then I wouldn't start again, but I would like for start to work like a restart if the server is already there.


Solution

  • We ended up with using a file that is created when the server is to be killed, then on the server process we periodically check if the file exists, if it's there we kill the server.