DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Getting Started With JPA/Hibernate

Trending

  • How Rule Engines Transform Business Agility and Code Simplicity
  • Fact-Checking LLM Outputs Programmatically: Building a Verification Layer That Catches Hallucinations
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  1. DZone
  2. Coding
  3. Java
  4. Properly Shutting Down An ExecutorService

Properly Shutting Down An ExecutorService

This tutorial will teach you that you don't need to pilot an A-Wing to shut down these ExecutorServices.

By 
T Tak user avatar
T Tak
·
Updated Apr. 14, 16 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
75.3K Views

Join the DZone community and get the full member experience.

Join For Free

I was recently working on an application that used hibernate for db access and lucene for storing and searching text. This combination was really great. It made searching really fast. And tomcat was used as the application container.

Sometimes I used to get this exception on redeploy:


java.lang.IllegalStateException: Pool not open
        at org.apache.commons.pool.BaseObjectPool.assertOpen(BaseObjectPool.java:123)
        at org.apache.commons.pool.impl.GenericObjectPool.returnObject(GenericObjectPool.java:898)
        at org.apache.commons.dbcp.PoolableConnection.close(PoolableConnection.java:80)
        at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.close(PoolingDataSource.java:180)
        at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.closeConnection(LocalDataSourceConnectionProvider.java:95)

And also on redeploy tomcat used to complain that it could not stop a thread:


SEVERE: The web application [/MyApp] appears to have started a thread named [myspringbean-thread-1] but has failed to stop it.This is very likely to create a memory leak

Here is the bean that created a thread to read some data from db and use lucene to index it.

I used ExecutorService to start the Thread on @PostConstruct. Here is the method that started the thread:

@PostConstruct
 public void init() {
  BasicThreadFactory factory = new BasicThreadFactory.Builder()
        .namingPattern("myspringbean-thread-%d").build();
  executorService =  Executors.newSingleThreadExecutor(factory);
  executorService.execute(new Runnable() {
   @Override
   public void run() {
    try {
     doTask();
    } catch (Exception e) {
     logger.error("indexing failed", e);
    }

   }
  });
  executorService.shutdown();
 }

And the @PreDestroy I used the executor service to shutdown. This was the first try that caused the above errors. This seemed to me that it should work fine. But it didn't.

@PreDestroy
 public void beandestroy() {
  if(executorService != null){
    executorService.shutdownNow();
  }
 }

After fighting for some time with the above errors, I came to the conclusion that the bean is destroyed and the above thread that was created was still running. So I started checking all the calls from this thread to find out if the interrupt was somwhere lost. But came to know that if the thread is doing some IO operations it is better to wait for them to finish before trying to shutdown the thread.

So I came up with the below @PreDestroy method and it works fine. Here the thread waits for a second for the IO to complete and then lets the spring to destroy this bean. And the thread itself checks for stopthread variable to not do any more IOs.

Instead of the stopThread variable an alternative would be to use Thread.currentThread().isInterrupted() in the thread loop. But for using this flag you need to be absolutely sure that the code you are calling in the thread is not resetting the interrupt status.


@PreDestroy
 public void beandestroy() {
  this.stopThread = true;
  if(executorService != null){
   try {
     scheduler.shutdownNow();
    // wait 1 second for closing all threads
    executorService.awaitTermination(1, TimeUnit.SECONDS);
   } catch (InterruptedException e) {
    Thread.currentThread().interrupt();
   }
  }
 }

Here is the complete Spring bean:


package com.tak.package;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

@Component
public class MySpringBean {

 private static final Logger logger = org.apache.logging.log4j.LogManager
   .getLogger(MySpringBean.class);

 private ExecutorService executorService;

 private volatile boolean stopThread = false;

 @PostConstruct
 public void init() {
  BasicThreadFactory factory = new BasicThreadFactory.Builder()
        .namingPattern("myspringbean-thread-%d").build();
  executorService =  Executors.newSingleThreadExecutor(factory);
  executorService.execute(new Runnable() {
   @Override
   public void run() {
    try {
     doTask();
    } catch (Exception e) {
     logger.error("indexing failed", e);
    }

   }
  });
  executorService.shutdown();
 }

 private void doTask()  {
  logger.info("start reindexing of my objects");
  List<MyObjects> listOfMyObjects = new MyClass().getMyObjects();
  for (MyObjects myObject : listOfMyObjects) {
   if(stopThread){ // this is important to stop further indexing
    return;
   }
   DbObject dbObjects = getDataFromDB();
   indexDbObjectsUsingLucene(dbObjects);
  }
 }


 @PreDestroy
 public void beandestroy() {
  this.stopThread = true;
  if(executorService != null){
   try {
    // wait 1 second for closing all threads
    executorService.awaitTermination(1, TimeUnit.SECONDS);
   } catch (InterruptedException e) {
    Thread.currentThread().interrupt();
   }
  }
 }
}

Spring Framework application Apache Tomcat Lucene Data (computing) Hibernate Container

Published at DZone with permission of T Tak. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Getting Started With JPA/Hibernate

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook