Using threads for lengthy operations

Most of the operations we encountered so far are not considerably time consuming. Especially loading or saving documents however, can be a lengthy task depending on the amount of data to be processed. Without any special handling of these tasks, application SimplyHTML could block for the time a particular save or load process would take. Java provides a mechanism to overcome this potential problem with class Thread.

Threads

Usually all activities of an application are done within the event dispatching thread. All lines of code contained in a method called by the event dispatching thread are executed sequentially in the order they are coded. In Java however, this must not be the case always. By opening a new Thread object and starting the code placed in its run method, this piece of code is executed in parallel or at least asynchonous from the event dispatching thread.

How SimplyHTML uses threads

In SimplyHTML three operations are executed in separate threads so far: saving a document to a file, loading a document from a file and closing one or more documents. All operations are embedded in an inner class of the respectice Actions SHTMLFileSaveAction, SHTMLFileOpenAction, SHTMLFileSaveAsAction and SHTMLFileCloseAction.

The inner classes FileSaver, NewFileSaver, FileLoader are subclasses of class Thread and simply wrap the call to saveDocument or loadDocument respectively in the run method inherited from the Thread class. Once an action is fired, its actionPerformed method creates an instance of FileSaver, NewFileSaver or FileLoader and calls its start method.

In addition, method scheduleClose in SHTMLFileCloseAction creates a Timer thread for each close operation waiting for a save operation to complete.