Search code examples
javatimersingletonfriend

How to make a TimerTask access privates of a singleton?


In my Java project, a singleton class needs to update regularly. This is done by setting a Timer on creation. But this means that the update function must be public. Only the timer task should be able to call it. How can I solve this?

public class MySingleton {

    private TimerTask updateMySingletonTask = new UpdateMySingletonTask();
    private static Timer timer = new Timer();
    private MySingleton mySingleton = null;

    public MySingleton() {
        timer.schedule( updateMySingletonTask, 1000, 1000);
    }    

    public static MySingleton getInstance() {
        if ( mySingleton == null )
            mySingleton = new MySingleton();
        return mySingleton;
    }
    public update() {
        // ...
    }
}

class UpdateMySingletonTask extends TimerTask {
    @Override
    public void run() {
        MySingleton.getInstance().update();
    }
}

I'm new to Java and very grateful if you point out other (potential) problems with my code!


Solution

  • You could make your UpdateMySingletonTask a private inner class of MySingleton or an anonymous inner class inside of MySingleton. Then all methods of MySingleton, even private ones, will be available to it.