Question

I'm building an application using JAVAFX over JAVA8. In my app i have a data grid that should populate with result set from the DB. However, the query may take a while and I don't want the GUI to be idle until that.

What is the best Thread architecture for that kind of issue?

I thought about using a Task for the query itself and than put the outcome it in the data grid. However, The main UI Thread doesn't allows other thread to touch the objects. And if I just wait for the thread to end, it becomes a sync process (which i want to avoid of)

Any Ideas?

Was it helpful?

Solution

I would go for that task. It is always a good idea to have long running operations on the background so the UI doesn't freeze up. Furthermore, you can think about paging (by scrolling down in a table for example, or prev and next buttons)

Here is how I would do it using a Task

    final Task<List<User>> searchUserTask = new Task<List<User>>() {
        @Override
        protected List<User> call() throws Exception {
              //search logic, for example call to DB
              return //list of users
        }

    };

    //Here we add a listener to the state, so that we can know when the operation finishes, and decide what to do after
    searchUserTask.stateProperty().addListener((ObservableValue<? extends Worker.State> source, Worker.State oldState, Worker.State newState) -> {

        if (newState.equals(Worker.State.SUCCEEDED)) { //the operation finished successfully
            List<User> result = searchTask.getValue();
            //set value to a UI component (this method runs on the UI thread)
            //usersTable.getItems().setAll(matches);
        } else if (newState.equals(Worker.State.FAILED)) {
            Throwable exception = searchTask.getException();
            log.error("Contact search failed", exception);
        }
    });

    new Thread(searchUserTask).start();

So here you have a way that somewhat simulates a callback mechanism. You add a listener to the state, when it changes, the event will automatically fire, and its upto you to properly catch it, and than handle the success state etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top