jeudi 21 juillet 2016

Design Pattern for java threading

I have a background service that has a thread running every 15 seconds and doing some work.

public class CacheCleaner implements Runnable, BackgroundService {
    ....

    @Override
    public void run() {
      ....
    }
}

BackgroundService is another interface that I have defined with methods that I want every background service in the system to implement.

public interface BackgroundService
{
   String getName();
   void start(long initialDelay);
   .....
}

The problem is that I want to do some work (3-4 lines of basic code) in the run method of every such class (there are 10-15 of them). Is there a design pattern or any better way I can achieve this rather than copy pasting the 4 lines in each of the 15 run methods?

NOTE: I mention the run() method since I only want those 4 lines of code to be executed when the thread is active.

Aucun commentaire:

Enregistrer un commentaire