I have a Client-Server application, where the server naturally processes requests in different newly created streams, and the client simply sends and receives data in one stream using Socket. But for example, I send a file that delays the stream and freezes the entire GUI for a few seconds, if not more.

But all the commands I have consist of requests, maybe something will happen to the server or a slow Internet connection and the GUI will fail?

Is it correct to process each button of the client in a separate thread to prevent GUI delay?

    1 answer 1

    I would recommend in a separate thread to make a queue to which you add tasks. When you click on the button, send to the command queue. And there to read commands and send by socket. In the simplest version of something like this:

    public class Worker extends Thread { private static final int SLEEPING_TIME = 50; private ConcurrentLinkedQueue<Command> mCommands = new ConcurrentLinkedQueue<Command>(); public void addCommand(Command cmd){ mCommands.add(req); } public void run() { while(true){ if(mCommands.size() > 0 ){ Command req = mCommands.poll(); // здесь пишем в сокет что-то } try { Thread.sleep(SLEEPING_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } } } 

    In the main thread, run this thread:

     Worker worker = new Worker(); worker.start(); 

    By pressing the button, call:

      worker.addCommand(new Command(...)); 

    Command your class of some kind, which in itself contains the data for the request.

    • Yes, a good solution, but in fact this solution is simply more elegant, but it’s not much slower to work than just to create a thread right away and start each time you press a button? Well, for example @FXML void someHandler () {new Thread (new Runnable () {"@" Override public void run () {// some code here ....}) .start (); } just with your decision, I will have to rework a lot of things, but if it is really very different, then it will be necessary - Oleg Morozov
    • @Oleg Morozov if there are few requests for a socket, then you can create a one-time Runnable for each task. - Suvitruf
    • Well, I have an automatic request once a second, plus the user sometimes (on average once every 30 seconds) when interacting with the UI sends requests. Well, in general I understood about this, my main question is not how to create threads, but in general it is the norm that If in the interface of key buttons, sliders and so on, there are 15 pieces that send requests to the server, then is it normal that each of them is processed in a separate stream? - Oleg Morozov