dmolony dmolony - 4 months ago 34
Java Question

How does getHostAddress() block other threads?

I want to display the local network address of the currently running javafx program, but even when I put the call in a separate thread it still seems to be blocking the UI thread. How is this even possible?

The main program has a menu option:

getIPAddress.setOnAction (e -> new Thread (new IPAddress (game)).run ());

Which executes this object:

public class IPAddress implements Runnable
private final Game game;

public IPAddress (Game game)
{ = game;

public void run ()
String ipAddress = InetAddress.getLocalHost ().getHostAddress ();
Platform.runLater ( () -> game.receiveIPAddress (ipAddress));
catch (UnknownHostException e)
e.printStackTrace ();

The code works, but it blocks the game's UI for several seconds.

nos nos

You're calling the run() method directly, so run() executes in your UI thread until it's done, not in a separate thread as you intended.

You need to start() your thread instead:

new Thread (new IPAddress (game)).start()