Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exchange data in real time over AJAX with multiple threads

I am developing an application in JSF 2.0 and I would like to have a multiline textbox which displays output data which is being read (line by line) from a file in real time.

So the goal is to have a page with a button on it that triggers the backend to start reading from the file and then displaying the results as it's reading in the textbox.


I had thought about doing this in the following way:

Have the local page keep track of what lines it has retrieved/displayed in the textbox so far.

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

This will continue until the entire file has been completely retrieved.


The issue is that the bean method that reads from the file is running a while loop that blocks. So to read from the data structure it is writing to at the same time will require using additional Threads, correct? I hear that spawning new Threads in a web application is a potentially dangerous move and that Thread pools should be used, etc.

Can anyone shed some insight on this?


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

like image 699
idolize Avatar asked Jun 14 '11 20:06

idolize


1 Answers

Have you considered implementing the Future interface (included in Java5+ Concurrency API)? Basically, as you read in the file, you could split it into sections and simply create a new Future object (for each section). Then you can have the object return once the computation has completed.

This way you prevent having to access the structure while it is still being manipulated by the loop and you also split the operations into smaller computations reducing the amount of time locking occurs (total lock time might be greater but you get faster response to other areas). If you maintain the order in which your Future objects were created then you don't need to track line #'s. Note that calling Future.get() does block until the object is 'ready'.

The rest of you're approach would be similar - make the Ajax call to get content of all 'ready' Future objects from a FIFO queue.

I think I understand what you're trying to accomplish.. maybe a bit more info would help.

like image 81
plafond Avatar answered Oct 04 '22 03:10

plafond