Real-time AJAX data exchange with multiple threads

I am developing an application in JSF 2.0 and I would like to have a multi-line text box that displays the output that is read (in turn) from a file in real time.

Thus, the goal is to have a page with a button that launches a backend to start reading from a file, and then display the results when reading in a text box.


I thought of it as follows:

Ask the local page to keep track of which lines it received / displayed in the text box.

Periodically, the local page will poll the backend using AJAX and request any new data that has been read (tell which lines on this page so far and only retrieve new lines since then).

This will continue until the entire file is completely restored.


The problem is that the bean method that reads from the file starts the while loop, which blocks. Therefore, to read from the data structure that she writes, at the same time, additional streams will be required, right? I heard that the emergence of new threads in a web application is a potentially dangerous move and that thread pools should be used, etc.

Can anyone shed some light on this?


Update: I tried a couple of different things with no luck. But I managed to get it working by creating a separate Thread to start my lock cycle, while the main thread could be used to read from it whenever an AJAX request is processed. Is there a good library that I could use to do something similar to this that still gives the JSF some lifecycle control over this Thread ?

+6
source share
1 answer

Have you considered implementing a Future interface (included in the Java5 + Concurrency API)? Basically, when you read in a file, you can split it into sections and just create a new Future object (for each section). Then you can return the object after the calculation is complete.

This way you avoid accessing the structure while it is still being processed by the loop, and you also break the operations into smaller calculations, reducing the amount of time lock (the total lock time may be longer, but you get a faster response to other areas). If you maintain the order in which your Future objects were created, you do not need to track line #. Note that the call to the Future.get () function is blocked until the object is ready.

The rest of your approach will be similar: make an Ajax call to retrieve the contents of all the ready-made Future objects from the FIFO queue.

I think I understand what you are trying to accomplish. Maybe a little more information will help.

+1
source

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


All Articles