Gaurav Keswani Gaurav Keswani - 4 months ago 12
Java Question

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.

Answer

You can use inheritance ... for example,

public abstract class AbstractBaseRunnable implements Runnable {
    ...
    @Override
    public void run() {
        ... // base work here!
    }
}

public class CacheCleaner extends AbstractBaseRunnable implements BackgroundService {
    ...
    @Override
    public void run() {
        super.run();
        ... // particular work for CacheCleaner here!!
    }
}