Hello, i am trying to make a java application where the application sends a message to a database and then waits for a new item in the database. I tried doing a while(true) loop however that did not work. I have looked into threads but I am left very confused. How can I call a function that updates a message list when a function finds that a new item has been added to the database?
Thank you
Before I begin, I advise that you learn more about threads (and maybe Java itself) before delving into a framework such as Vaadin. There are probably a billion Java tutorials online, so I won’t link any here.
The following is a really bad approach to continuously query the DB for changes, so please allow others to offer you better solutions. Here’s a good place to start…
How to create a thread:
new Thread(() -> {
SOME THREAD CODE
}).start();
Vaadin has it’s own UI thread, which must be accessed from within other threads with UI#access. You can read more about this here: https://vaadin.com/docs/latest/advanced/server-push. You will have to get the current UI instance from outside your thread:
UI ui = UI.getCurrent();
new Thread(() -> {
ui.access(() -> {
UPDATE UI
});
}).start();
So, you could do something like the following:
UI ui = UI.getCurrent();
new Thread(() -> {
while(true) {
QUERY DB
ui.access(() -> {
UPDATE UI
});
try {
Thread.sleep(5000);
} catch(InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}).start();
thank you so much ![]()
For periodically executed tasks I would use a ScheduledExecutorService instead of manually create a thread and put it to sleep