Friday, July 15, 2011

Tomcat shutdown fails after installing Solr

In this post I described how to add Solr to an existing web application and how to query the index using Sorlj. Everything seemed to work well, but after a while I started noticing that tomcat didn't shut down successfully anymore: it seemed to hang on shutdown.
The culprit seems to be the EmbeddedSolrServer I was using. Apparently you need to shutdown the CoreContainer that it's using for the server to successfully shutdown. What this means is we'll have to modify our search bean a bit. Add the following fields to the class:
private static final SolrServer solrServer = initSolrServer();
private static CoreContainer coreContainer;

The initSolrServer() method looks like this:
private static SolrServer initSolrServer() {
  try {
   CoreContainer.Initializer initializer = new CoreContainer.Initializer();
   coreContainer = initializer.initialize();
   EmbeddedSolrServer server = new EmbeddedSolrServer(coreContainer, "");
   return server;
  } catch (Exception ex) {
   logger.log(Level.SEVERE, "Error initializing SOLR server", ex);
   return null;

Finally we'll also add a shutdown method to the search bean:
 public static void shutdownSolr() {
  if (coreContainer != null) {

Now all we need to do is call the shutdownSolr() method on our search bean when the servlet container is shut down. For this we'll need to add a ServletContextListener to our web application. Open your web.xml and add the following lines:

And this is how the SolrListener should look like:
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class SolrListener implements ServletContextListener {

 public void contextDestroyed(ServletContextEvent arg0) {

 public void contextInitialized(ServletContextEvent arg0) {



And now Tomcat should shutdown without any problems!

No comments:

Post a Comment