Creating a maintenance thread in Spring

Recently we needed to reindex our data due to some changes. Here is how we did it.

We defined a file on the file system. If that file is present the reindexing thread runs, so it would easy for our deployment team to run reindexing when needed.

Here is the code creating the thread. 

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.springframework.stereotype.Component;

public class IndexMaintenance {

	private ExecutorService executorService;
	private File fileRepair = new File("/opt/setup/maintainindex.txt");
	public void init() {

	private void initRepairIndex() {
		if (fileRepair.exists()) {
			BasicThreadFactory factory = new BasicThreadFactory.Builder()
			executorService =  Executors.newSingleThreadExecutor(factory);
				//write your code here

	public void destroy() {
		if(executorService != null){
			// wait 3 second for closing all threads
			try {
				// wait 3 second for closing all threads
				executorService.awaitTermination(3, TimeUnit.SECONDS);
				// try again and let go
				if(!executorService .isTerminated()){
			} catch (InterruptedException e) {


So the above code creates and executorservice and then shuts it down gracefully on shutdown.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.