FlorianSchneiderman92 FlorianSchneiderman92 - 1 year ago 51
Java Question

What's the idea behind using Thread.Join() in this case?

I have a code of a small Java program which generates MD5 checksums. It can work only with one file at a time. When given a file name it opens a modal dialog where it shows the progress bar and the overall status. At "100%" this dialog closes, the program displays generated MD5 and then is ready to take another file.

The function which generates MD5 is located in the class which implements

and this class is then passed to
instance. Then this
object is used as
thread.start(); thread.join()
. The program works with only one file at a time. It works perfectly well when I use the function without threads.

My question is: what's the purpose of placing it in a separate thread and joining it?

Answer Source

As I have already mentioned in this answer, if you keep time-consuming tasks in the main GUI process of your program you should be aware that it will not respond to any user interaction as long as the task is running.

In this page you can find some good practices regarding asynchronous operations in Java applications (it is focused on Swing, but can be applied broadly for other Java coding strategies). I would like to highlight one of the topics:

Rule #2: do not run time-consuming operations on the event thread.

I'll keep repeating this: Swing uses a single thread for all GUI events. If your event handler is uploading a multi-megabyte file across the net, those events will be delayed until you're done. There is a balancing act involved with this rule: some operations (such as getting the size of a file) are so fast that they won't interrupt the user. However, that's not a reason to be cavalier, because some day your user will be getting the size of a file that resides on a fileserver that has an intermittent network connection.

As you have mentioned, the dialog is kept opened while the MD5 is being generated. That should be the reason why the developer used a separate thread -- even knowing the program can only handle one file at a time, by keeping the computation isolated in its own thread will avoid the main GUI from being frozen while the MD5 is computed.

However, Thread.join() allows one thread to wait for the completion of another. That said, the developer may have used this strategy to prevent additional user interaction until the MD5 calculation is complete. Or, what is also possible, to wait for the MD5 calculation to finish before the main program (or GUI) finishes (closes).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download