Reputation: 3
I have a ArrayList with urls pointing to html files that need to be downloaded and displayed. Right now I'm just looping through the ArrayList and downloading all files on the Main Thread.
After all files have been downloaded, I display the first html page in a jxbrowser. I also made "next" and "prev" buttons so the user can cycle through the html pages.
Currently I need to wait till all Files have been downloaded and sometimes it takes a really long time. I would like to download all the Files in seperate Threads and to display the first page after it has been downloaded. Other files would continue to download in background. If the user clicks on next button and the Thread downloading that file isn't completed, user should get a an error Message.
I have no clue how to accomplish this as i´m a beginner in java so any help would be appreciated.
Upvotes: 0
Views: 100
Reputation: 340138
Giving an error to a user when they perform a correct action like pressing your Next button is poor interface design.
I suggest creating dummy page content that explains that target URL is loading. Create as many of these pages as you have URLs in your list of downloads. Display those dummy pages to the user initially.
Store the content for those dummy pages in a thread-safe Map
implementation, such as ConcurrentHashMap
. The key for the map should be the URLs to be downloaded. The values of the map would be the page content. Initially all the values are the dummy page. Then using background threads, you replace each dummy page with the content of a successfully downloaded page.
Use an executor service to perform the downloads. Submit one instance of the downloader for each URL, as the Runnable
/Callable
task.
As each task completes, put the page content into the map to replace the dummy page.
Then use the JavaFX mechanism to ask the user-interface thread to update its display, transitioning from the dummy page to the downloaded page. Never access or modify the user-interface widgets from a background thread. For more info, search Stack Overflow for posts such as Complex concurrency in JavaFX: using ObservableLists and Properties from multiple worker threads.
Remember to gracefully shut down the executor service. Otherwise its backing pool of threads may continue to run indefinitely like a zombie 🧟♂️.
All of these topics have been addressed many times already on Stack Overflow. So search to learn more.
Upvotes: 1