Search code examples
javascheduled-tasksrunnablescheduledexecutorservice

ScheduledExecutorService executed only once with a switch statement


I've a problem which is very strange to me. I made an implementation of Runnable, to be executed with ScheduledExecutorService. Problem is, it executes only one time...

Here is the useful code (ev is an enumeration):

private class MenuEventsListener implements Runnable    {
    @Override
    public void run() {
        System.out.println("Next iteration...");
        switch(ev)  {
            case DESIGNER:
                foo();
            break;
            case EXIT:
                dispose();
                System.exit(0);
            break;
        }
        ev = MenuEvents.ENUM_LAST;  
    }
}

And the funny thing, is that if I replace that switch by some if-else statements, it works fine, meaning that this Runnable is executing every 50ms as I asked..!

private class MenuEventsListener implements Runnable    {
    @Override
    public void run() {
        System.out.println("Next iteration...");
        if (ev == MenuEvents.DESIGNER)
            foo();
        else if (ev == MenuEvents.EXIT) {
            dispose();
            System.exit(0);
        }
        ev = MenuEvents.ENUM_LAST;      
    }
}

Here is the scheduling setup:

    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleAtFixedRate(new MenuEventsListener(), 
            0, 50, TimeUnit.MILLISECONDS);

Why the Runnable is called each 50ms with a if-else statement, and why it is called only one time with a switch ??

EDIT: Because you asked, here is the declaration of MenuEvents and ev:

public enum MenuEvents  { 
    DESIGNER, CONFIG, ABOUT, BACKMENU, EXIT, ENUM_LAST
};
public MenuEvents;

Yes, with ENUM_LAST I'm trying to reproduce the C convention, but there I also use it as a sort of NULL value.


Solution

  • I don't see your full code but I am pretty sure that the ev variable is null the first time that you Runnable is executed.

    As a result, the switch statement throws a NullPointerException which kills your thread.

    In the case of the if-else block, neither the if block or the else if blocks are executed and finally ev is assigned the value of ENUM_LAST.