Question

Below is my Interface -

public interface IClient {
    public String read(ClientInput input);
}

This is my Implementation of the Interface -

public class TempClient implements IClient {

    @Override
    public String read(ClientInput input) {

    }
}

Below is my factory code -

public class TempClientFactory {

    public static IClient getInstance() {
    // new TempScheduler().startScheduler();
    return ClientHolder.INSTANCE;
    }

    private static class ClientHolder {
        private static final TempClient INSTANCE = new TempClient();
    }
}

Now I have a factory which gets the instance of TempClient like this so customer will use our factory like below while making the call to our code.

IClient client = TempClientFactory.getInstance();
client.read(input);

And below is my background thread code -

public class TempScheduler {

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        public void startScheduler() {
            final ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(new Runnable() {
                public void run() {
                try {
                    callServers();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                }
            }, 0, 500, TimeUnit.SECONDS);
        }
    }

    //... some code
}

Problem Statement:-

  1. Now I have a background thread which will be running behind the scene which fetches the data from the URL, parses it and stores it in a variable. Now what I want is as soon as our customer starts making a call to use our code by using the factory, I want the background thread to get started. So I thought I can put the background thread call in my factory getInstance method.. Is that the right place to put there?
Was it helpful?

Solution

I think yes, put it in getInstance() and call it only the first time this method is called. I think this is what you want.

OR

If you're using some framework and that framework is sending you an event when the app is initialized/ready, then you can also hook there and do it there. But in that case it may start executing even before the customer has called getInstance(). It's up to you to decide if that's OK or not.

The latter is better IMHO.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top