Stop a loop in code from UI

Unable to stop a while loop in code from UI. Such as on button click - but the listener is fired only after complete loop execution.

Thanks in advance.

Hi dinesh,

you may want to break your loop.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

Atleast read the question before reply ’
I want to break the loop from UI on button click’.

Hello dinesh,

at least you should write a real question and read how Java and threads work.

Hi, it does not really make sense to do what you want to do. Vaadin uses a lock to synchronize concurrent access to the user session, so if you simply loop eternally in a thread handling a request, the session also stays locked eternally and nothing else can access it.

If you really need a busy loop somewhere in your application logic, it should be in a separate thread that only acquires the session lock when it really needs it, and communicates with your event handlers using proper synchronization primitives.

Don’t really your use case, made below small code, hopefully it answers your question somehow. The basic idea is that your while loop should be in a separate thread.

    private volatile static boolean stop = false;

    @Override
    protected void init(VaadinRequest request) {
        final VerticalLayout layout = new VerticalLayout();
        layout.setMargin(true);
        setContent(layout);

        Button button = new Button("Click Me");
        button.addClickListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                stop=true;
                Notification.show("stop");
            }
        });
        layout.addComponent(button);
        
        new Thread(){
            public void run() {
                int count = 0;
                while(true){
                    if(stop)
                        return;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(""+count++);
                }
            };
        }.start();
    }

Thanks Johannes and Haijian.