Javafx WebEngine: what actually happens in the background? The user interface hangs on loadContent (large HTML document)

From WebEngine docs:

Download always takes place in the background thread. The methods that initiate the download are returned immediately after scheduling the background job. Track progress and / or cancel a job, use the Worker instance available from the getLoadWorker () method.

I have an HTML string that I load into a WebView via WebEngine.loadContent(String). This line is about 5 million characters. After running this in Platform.runLater()(and I have to run it in the JavaFX thread, otherwise I will get an error), my user interface freezes for a minute.

If I do not run it in Platform.runLater(), I get:

java.lang.IllegalStateException: Not on FX application thread; currentThread = populator
    at com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:236)
    at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:423)
    at javafx.scene.web.WebEngine.checkThread(WebEngine.java:1216)
    at javafx.scene.web.WebEngine.loadContent(WebEngine.java:931)
    at javafx.scene.web.WebEngine.loadContent(WebEngine.java:919)
    ...

webEngine webEngine.getLoadWorker().getProgress() webEngine.getLoadWorker().cancel(), JavaFX, ...

, , Platform.runLater(()->webEngine.getLoadWorker().getProgress()), ( -), 1.0 ...

, , :

// WebView
wvIn.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
    class ProgressThread extends Thread {
        private Worker.State loadWorkerState;

        synchronized Worker.State getLoadWorkerState() {
            return loadWorkerState;
        }

        synchronized void setLoadWorkerState(Worker.State loadWorkerState) {
            this.loadWorkerState = loadWorkerState;
        }

        {
            setDaemon(true);
            setName("LoadingWebpageProgressThread");
        }

        public void run() {
            while (true) {
                try {
                    if (getLoadWorkerState() == Worker.State.RUNNING)
                        // piWv ProgressIndicator (WebView loading)
                        Platform.runLater(() -> piWv.setVisible(true));
                    while (getLoadWorkerState() == Worker.State.RUNNING) {
                        Platform.runLater(() -> {
                            piWv.setProgress(wvIn.getEngine().getLoadWorker().getProgress());
                            // TODO delete
                            System.out.println(wvIn.getEngine().getLoadWorker().getProgress());
                        });
                        Thread.sleep(100);
                    }
                    if (getLoadWorkerState() == Worker.State.SUCCEEDED) {
                        Platform.runLater(() -> piWv.setProgress(1d));
                        Thread.sleep(100);
                        Platform.runLater(() -> {
                            piWv.setVisible(false);
                            piWv.setProgress(0d);
                        });
                    }
                    synchronized (this) {
                        wait();
                    }
                } catch (InterruptedException e) {
                }
            }
        }
    };

    final ProgressThread progressThread = new ProgressThread();
    {
        progressThread.start();
    }

    // executed on JavaFX Thread
    @Override
    public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
        if (newValue == State.SUCCEEDED) {
            JSObject window = (JSObject) wvIn.getEngine().executeScript("window");
            window.setMember("controller", mainController);
            progressThread.setLoadWorkerState(newValue);
            progressThread.interrupt();
        } else if (newValue == State.RUNNING) {
            progressThread.setLoadWorkerState(newValue);
            progressThread.interrupt();
        }
        // TODO delete
        System.out.println(oldValue + "->" + newValue);
    }
});

?

JavaFX? WebView?

+4
2

HTML , , .

-, . , . , , , deadlock -prone, .

, events. - , ProgressThread . ChangeListener , JavaFX Application Thread; .

indicator.setVisible(false); // Start hidden
engine.getLoadWorker().progressProperty().addListener((observable, oldValue, newValue) -> {
    indicator.setProgress(newValue.doubleValue());
    indicator.setVisible(indicator.getProgress() != 1D);
});

binding:

Worker<Void> worker = engine.getLoadWorker();
indicator.visibleProperty().bind(worker.stateProperty().isEqualTo(Worker.State.RUNNING));
indicator.progressProperty().bind(worker.progressProperty());

JavaScript- : , , , .

engine.documentProperty().addListener((observable, oldValue, newValue) -> {
    if (newValue == null) {
        return;
    }
    JSObject window = (JSObject)engine.executeScript("window");
    window.setMember("controller", mainController);
});

, . , HTML-: - , , -, , , , .

+1

...

Http- load loadContent ( : ):

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.zip.GZIPOutputStream;

public class BadHttpServer {
    private static int request = 0, connection = 0;
    private static final BadHttpServer SINGLETON = new BadHttpServer();
    private ServerSocket serverSocket;
    private String htmlString, formattedDate;
    private byte[] compressedHTML;

    public String getURL() {
        return "http://localhost:60000";
    }

    synchronized byte[] getCompressedHTML() {
        return compressedHTML;
    }

    synchronized void setCompressedHTML(String string) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream(string.length() / 2);
                GZIPOutputStream gos = new GZIPOutputStream(baos);) {
            gos.write(string.getBytes("utf-8"));
            gos.close();
            this.compressedHTML = baos.toByteArray();
            formattedDate = String.format(Locale.US, "%1$ta, %1$td %1$tb %1$tY %1$tH:%1$tM:%1$tS %1$tZ",
                    Calendar.getInstance(TimeZone.getTimeZone("GMT")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private synchronized String getFormattedDate() {
        return formattedDate;
    }

    private BadHttpServer() {
        try {
            serverSocket = new ServerSocket(60000);
        } catch (IOException e) {
            e.printStackTrace();
        }
        new Thread() {
            {
                setDaemon(true);
                setName("serverSocketThread");
            }

            public void run() {
                while (true) {
                    try {
                        new Thread(acceptAndSendHTML(serverSocket.accept())) {
                            {
                                setDaemon(true);
                                setName("acceptThread" + connection++);
                            }
                        }.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
        }.start();
    }

    protected Runnable acceptAndSendHTML(final Socket socket) {
        return new Runnable() {
            @Override
            public void run() { 
                try (BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "ASCII"));
                        BufferedWriter asciiWriter = new BufferedWriter(
                                new OutputStreamWriter(socket.getOutputStream(), "ASCII"));
                        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream(), 1000)) {
                    while (!socket.isClosed()) {
                        int request = BadHttpServer.request++;
                        // READING
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.append(br.readLine() + "\r\n");
                        for (String line = ""; !(line = br.readLine()).isEmpty(); stringBuilder.append(line + "\r\n"))
                            ;
                        // TODO delete
                        System.out.print("Connection " + request + " request: " + stringBuilder);
                        // WRITING
                        byte[] compressedHTML = getCompressedHTML();
                        asciiWriter.write("HTTP/1.1 100 Continue\r\n");
                        asciiWriter.write("\r\n");
                        asciiWriter.write("HTTP/1.1 200 OK\r\n");
                        asciiWriter.write("Date: " + getFormattedDate() + "\r\n");
                        asciiWriter.write("Content-Type: text/html; charset=utf-8\r\n");
                        asciiWriter.write("Content-Encoding: gzip\r\n");
                        asciiWriter.write("Content-Charset: utf-8\r\n");
                        asciiWriter.write("Content-Length: " + compressedHTML.length + "\r\n");
                        // TODO delete
                        System.out.println("Content-Length: " + compressedHTML.length + "\r\n");
                        asciiWriter.write("\r\n");
                        asciiWriter.flush();
                        for (int writtenOverall = 0, writtenThisIteration = 0; writtenOverall < compressedHTML.length; writtenOverall += writtenThisIteration) {
                            bos.write(compressedHTML, writtenOverall,
                                    writtenThisIteration = Math.min(compressedHTML.length - writtenOverall, 1000));
                            Thread.sleep(10); // Bandwidth throttling
                        }
                        bos.flush();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
    }

    public static BadHttpServer getIntance() {
        return SINGLETON;
    }

    public synchronized void setHtmlString(String htmlString) {
        this.htmlString = htmlString;
        setCompressedHTML(htmlString);
    }

    synchronized String getHtmlString() {
        return htmlString;
    }

}

loadContent

BadHttpServer.getIntance().setHtmlString(htmlString);
Platform.runLater(() -> wvIn.getEngine().load(BadHttpServer.getIntance().getURL()));

- loadWorker RUNNING SUCCEDED:

via BadHttpServer:
javascript and style after body: 13,5 s
javascript and style before body: 8,6 s

so I continued to test with javascript and style before body.
without javascript injection: 8,5 s

I continued to test with javascript injection.

Next I did with loadContent: 170 s - no UI resposivness during loading
Yep - almost 3 minutes...

So I returned back with BadHttpServer.
Next I tried "throttling the bandwidth" by changing the sleep time.
no sleep: 8,2 s
5 ms sleep: 6,8 s
10 ms sleep: 6,7 s
20 ms sleep: 11,6 s

In these cases the UI was responsive, although it was lagging a bit.
The progressIndicator showed nicely, pausing a bit at 90%.
By increasing the sleep time, the UI was more responsive.

, , loadContent , - , ...

0

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


All Articles