R
R
Romario212018-07-30 11:42:04
Java
Romario21, 2018-07-30 11:42:04

Java access to main thread?

Framework : Vaadin flow
Comrades help.
The task is to periodically start receiving data in the stream and send a message to the main class (Eventbus).
Here is my code, it crashes on sending a message:

Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println("timer: "+Thread.currentThread());
                Callable task = () -> {
                   //Выполняем какую-то фигню возвращающую результат
                    Login login = new Login();
                    login.setMESSAGE(MessageCode.LOGIN_ERROR);
                    return login;
                };
                ExecutorService executor = Executors.newSingleThreadExecutor();
                Future<Login> future = executor.submit(task);
                try {
                    Login message = future.get();
                    MainView.eventBus.post(message);//Кидаем сообщение

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                executor.shutdown();
            }
        }, 0, 3500);

If you take the code out of the timer, then everything is fine.
Here is what is output to the console:
SEVERE [Timer-0] com.google.common.eventbus.EventBus$LoggingHandler.handleException Exception thrown by subscriber method taskAutorization(Objects.Login) on subscriber
java.lang .IllegalStateException: UI instance is not available. It means that you are calling this method out of a normal workflow where it's always implicitely set. That may happen if you call the method from the custom thread without 'UI::access' or from tests without proper initialization.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sergey, 2018-12-16
@Romario21

look for
asyncExec()
(like
.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
- this is for SWT
for Swing see
invokeLater()
for JavaFx I don't remember but if you find the first two you'll figure it out yourself I hope

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question