Search code examples
javamultithreadingconcurrencyjava.util.concurrentservlet-listeners

Calling method of Another class from run() method


I have created a scheduler which calls run method.

@WebListener
public class BaclkgroundJobManager implements ServletContextListener {

    private ScheduledExecutorService scheduler;
    public void contextInitialized(ServletContextEvent sce)  { 

        scheduler=Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new SomeMinuteJob(), 0, 5, TimeUnit.MINUTES);      
     }
}

this calls to

public class SomeMinuteJob implements Runnable {

    @Override
    public void run() {
        
        System.out.print("Inside run method");
            ReadData obj= new ReadData();
            obj.readData();
            System.out.println("After reading data");
            }       

}

I have created ReadData class below.

public class ReadData
{
   public void readData()
   {
     System.out.println("I am inside readdata");
   }
}

So I have created object of ReadData inside the run() mehthod and I have called its method. But control is not coming to ReadData class. it is not printing the content inside readData() method. Even I created constructor and put some content but even though that is not printing. How can I resolve that? Control is going inside run and it is printing Inside run method


Solution

  • A common problem with ScheduledExecutorService is that if the scheduled command throws an exception, the exception is silently swallowed. The code in the question does not seem to throw exceptions, but in more complex code it is difficult to avoid (for example unexpected NullPointerExceptions)

    A quick fix is to put all of the Runnable.run method in a try-catch block:

    public class SomeMinuteJob implements Runnable {
        @Override
        public void run() {
            try {
                System.out.print("Inside run method");
                ReadData obj = new ReadData();
                obj.readData();
                System.out.println("After reading data");
            } catch (Exception e) {
                // Log exception
                e.printStackTrace();
            }
        }
    }