Using the JavaFX Application.stop () Method for Shutdownhook

So, I use shutdownhook for cleaning, because it is not always guaranteed that shutdownhooks thread is executed, should I just click this code on the JavaFX Application Thread (stop () method), which is executed every time I close the application? The code is not expensive, to start it basically only a close socket, if it is not closed and does not kill processes, if not killed.

Is it good to use Application.stop () to clear ShutdownHook?

Quote from the doc:

This method is called when the application stops and provides a convenient place to prepare for the exit and destruction of the Resources application. The implementation of this method is provided. The application class does nothing.

NOTE. This method is called in the JavaFX application thread.

Is this method only for cleaning user interface resources? So far, I see no reason to use shutdownhook over stop () at all.

+4
source share
1 answer

stop()It is called only when you exit the application through Platform.exit()(or when the last window closes, if Platform.implicitExit- true). Shutdown switches will be executed if called System.exit(), or if the native process that starts the JVM is interrupted (for example, ctrl-C on a * nix-like OS), in addition to the usual way to exit a JavaFX application.

stop() FX, (, " " ..). , (, FX Toolkit, , ).

, .

, :

import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class ShutdownTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        Button platformExit = new Button("Platform Exit");
        platformExit.setOnAction(e -> Platform.exit());
        Button systemExit = new Button("System Exit");
        systemExit.setOnAction(e -> System.exit(0));
        Button hang = new Button("Hang");
        hang.setOnAction(e -> {while(true);});
        HBox root = new HBox(5, platformExit, systemExit, hang);
        root.setPadding(new Insets(20));
        root.setAlignment(Pos.CENTER);
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    @Override
    public void stop() {
        System.out.println("Stop");
    }

    public static void main(String[] args) {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> System.out.println("Shutdown hook")));
        launch(args);
    }
}

Mac OS X.

" ", Dock "Quit", stop(), hookdown.

" ", " " kill id , . , "Hang", "Force Quit", .

SIGKILL (kill -9 id kill -SIGKILL id ) stop(), .

+10

Source: https://habr.com/ru/post/1671455/


All Articles