Home >Database >Mysql Tutorial >How Can I Use JavaFX Threads to Efficiently Handle Database Requests?
Using threads to make database requests
JavaFX provides a concurrency API specifically designed for executing code in a background thread, with API specifically designed for updating the JavaFX UI on completion of (or during) the execution of that code. The key class in javafx.concurrent is Task, which represents a single, one-off, unit of work intended to be performed on a background thread. This class defines a single abstract method, call(), which takes no parameters, returns a result, and may throw checked exceptions. To correctly implement threading for database requests, the long-running operation (database access) should be performed in a background thread, returning the results of the operation when it is complete, and then schedule an update to the UI on the UI (FX Application) thread using Platform.runLater(Runnable r) to execute r.run() on the FX Application Thread.
General Good Practices for Multithreading
Using the javafx.concurrent API
For example:
final int courseCode = Integer.valueOf(courseId.getText()); Task<Course> courseTask = new Task<Course>() { @Override public Course call() throws Exception { return myDAO.getCourseByCode(courseCode); } }; courseTask.setOnSucceeded(e -> { Course course = courseTask.getCourse(); if (course != null) { courseCodeLbl.setText(course.getName()); } }); exec.execute(courseTask);
The above is the detailed content of How Can I Use JavaFX Threads to Efficiently Handle Database Requests?. For more information, please follow other related articles on the PHP Chinese website!