Search code examples
javathread-safetyrunnable

Method returns runnable object


Can I do something like this in Java:

 protected Runnable getRunnable(final int seconds) {
    Runnable runnable = new Runnable() {
        public void run() {
                sendData();             
                try {
                    Thread.sleep(seconds * 1000);
                } 
                catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
        }
    };
    return runnable;
}

And then:

protected void startTimer(int seconds) throws InterruptedException,NullPointerException {
    Thread thread = new Thread(getRunnable(seconds));
    thread.start();
}

Is the aforementioned process safe??


Solution

  • In the comments you say

    All I'm trying to do is to execute sendData() method every a specific amount of seconds(i.e. every 15 seconds)

    Then use a built-in Timer which will organise that for you, for example:

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    Runnable r = new Runnable() {
        @Override
        public void run() {
            sendData();
        }
    };
    ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(r, 0, 15, TimeUnit.SECONDS);
    
    //when you want to cancel the scheduled task
    future.cancel(true);
    
    //and before you leave your program, don't forget to call:
    scheduler.shutdown();