Tuesday, May 15, 2012

Neo4J Tutorial #4: Registering a shutdown hook

In the previous tutorials on Neo4J, we discussed what Neo4J is, how to start it and use Cypher for basic queries and getting started with Neo4J and Java.  In the third of these, we had hinted there are some things you should do that are best practices in a proper environment.

To start this tutorial, please first follow the 3rd of the series from http://technoracle.blogspot.ca/2012/05/third-neo4j-tutorial-getting-started.html

You' notice that on Neo4J's pages, they discuss a shutdown hook.  So what exactly is that and why would anyone use it?

If you examine the code on the previous tutorial, you will see that you can shutdown a database by simply calling grapDB,shutdown();  These lines of code are shown above.  Note that calling shutown() only tries to shutdown the database.  The Shutdown hook simply ensures that the database shuts down cleanly.

To add a shutdown hook to the code in the previous tutorial, navigate to the createDB() method and register a shutdownhook handler right under the line where you create the database.  With the new line added, your code should look like this:

At this time, you may notice red X's as this introduces errors into the project.  We have registered a shutdown hook which takes a single argument of  the graphDB instance it will register the hook for.  Now it is time to write the hook.  

registerShutdownHook() is a static method that returns nothing (void).  The syntax above is a bit confusing given line 91 calls addShutDownHook on a new thread and closes around line 99, hence the erroneous looking but much required "});" syntax.  This essentially encapsulates the functionality.    The shutdown hook ensures that the Neo4j instance shuts down nicely when the VM exits (even if you "Ctrl-C" the running instance before it has finished running.  Try running this example now with the modifications and you should see the following print out in your console.

No comments:

Post a Comment

Do not spam this blog! Google and Yahoo DO NOT follow comment links for SEO. If you post an unrelated link advertising a company or service, you will be reported immediately for spam and your link deleted within 30 minutes. If you want to sponsor a post, please let us know by reaching out to duane dot nickull at gmail dot com.