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.io.File;
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;

@Component
public class IndexMaintenance {

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


	private void initRepairIndex() {
		if (fileRepair.exists()) {
			BasicThreadFactory factory = new BasicThreadFactory.Builder()
				     .namingPattern("indexMaintenance-repairthread-%d").build();
			executorService =  Executors.newSingleThreadExecutor(factory);
			executorService.execute(()->{
				//write your code here
			});
			executorService.shutdown();
		}
	}
	


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

}

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.