Home > Blockchain >  Java: Ignored RuntimeException with ScheduledExecutorService
Java: Ignored RuntimeException with ScheduledExecutorService

Time:01-26

Introduction

I'm currently working on a project that logs data from a website to a database every x hours.

But when the database connection properties are not good, the program does not throw a RuntimeException pretends everything is fine.

When we have a RuntimeException from the schedule, I have to stop the whole program and tell the user about the problem. The possible problem is invalid variable environment or a invalid properties from docker secret.

My code:

    private static ScheduledExecutorService executeWithPeriod(Runnable runnable, int period) {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.schedule(runnable, Math.max(1, period), TimeUnit.HOURS);
        return executor;
    }

The runnable takes care of getting data and saving it to the database.

The possible throwed RuntimeException:

  • DockerSecretVariableNotFoundException
  • EnvironmentVariableNotFoundException

All these exceptions extends RuntimeException

Someone have the solution to throws the RuntimeException to the main thread ?

CodePudding user response:

You haven't demonstrated a need for multiple threads, so you can eliminate the complexity of signaling between concurrent threads. Use a single thread instead:

final class YourTask {

    public static void main(String... args) throws InterruptedException {
        YourTask task = new YourTask();
        while (true) {
            try {
                task.doYourThing();
            } catch (Exception ex) {
                ex.printStackTrace();
                break;
            }
            TimeUnit.HOURS.sleep(1L);
        }
    }

    private void doYourThing() throws Exception {
        System.out.println("I'm saving data from a website to a database!");
        throw new RuntimeException("Oh no! I can't read my configuration!");
    }

}

Note that this solution "tells the user about the problem" and "stops the whole program," as specified.

CodePudding user response:

Well, since the task is just to tnrow a RuntimeException, how about this?

class MyRunnable implements Runnable {
    public void run() {
        throw new RuntimeException("mark my words");
    }
}

Rest assured this code throws an exception. You can try using this code:

public static void main(String[] args) {
    new MyRunnable().run();
}

However usually Runnables are run in their own thread:

new Thread(new MyRunnable()).start()

So now the exception is thrown as well. However it terminates the thread - and that's it.

I am coming back to my question from the comment: What are you trying to achieve?

  •  Tags:  
  • Related