Taming Swing Threads Part 3: The Swing Worker

The problem.

We problem we encountered at the end of part 2 is that although it is really easy to offload long run tasks to a background thread, it is rather difficult displaying the results in a thread safe manner.

 

Java™ 5 has recently provided us with a class called the SwingWorker, which solves this problem and at the same time shields us from the complexity of passing information between threads. The SwingWorker is the perfect solution to our problem. The SwingWorker offers a great deal of functionality; however for this blog entry I will only be showing you how to use it to solve the problem discussed above. If you want further information on the SwingWorker, you can check out its API on the sun site: http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html.

 

The SwingWorker contains a large number of methods that you will be making use of. There is a single method doInBackground() that you must implement. The methods process() and done() you can choose to override. While the methods publish() and get() you will use but not override.

 

Don’t panic if these methods look really hectic, they make far more sense when you see them in the context of the example.

 

protected abstract T doInBackground()

This method is executed on a background thread. It is expected to return the result of the long running process or throw an exception. This method is abstract and you are forced to implement it.

 

protected void publish(V... chunks)

This method should be called from the background thread while the long running task is executing. It is used to pass data to the process() method which executes on the EDT.

 

protected void process(List<V> chunks)

This method receives information from the publish() method. As it is executed on the EDT therefore it can be used to update the gui, during the execution of the background task. You should override this method if you need to provide feedback to the gui while the doInBackground() method is running.

 

protected void done()

The done() method is called once the doInBackground() method is complete. If you wish to perform some feedback once the background task is complete this is the method you should override. It is executed on the EDT and therefore can be used to update the gui.

 

public T get()

The method get() should be called from the done() method. It will either return the result from the doInBackground() method or it will throw an exception if an exception occurred during the doInBackground() method.

void execute()

This method is used to start the SwingWorker.

 

The example.

I believe I can tell you about how great the SwingWorker is until the cows come home, but I feel an example is the best way of explaining how to use it.

 

Lets assume we are writing a really simple application that scans and counts a list of files. During the scanning process the application must let the user know the name of the file it is scanning. Once all the files have been scanned, the total number of scanned files must be displayed to the user. All user feedback will take place through a JTextfield.

 

If we have a careful look at the above requirement, we should be able to assign different pieces of logic to 3 methods mentioned earlier.

  • The act of scanning a list of files should be performed on a background  thread, as this is a long running task and would block the Event Queue while executing. This logic should be placed in the doInBackground() method.
  • The requirement of displaying the name of the currently scanned file can not be performed on the background thread and should be placed in the process() method, which is executed on the EDT.
  • The requirement to display the final number of scanned files can also not be performed on the background thread and should be placed in the done() method, which is executed on the EDT.

 

Below is a code snippet that solves the above problem:

 

new SwingWorker<Integer, String>() {

 

     //runs on a background thread.

     protected Integer doInBackground() throws Exception {

          Integer fileCount = 0;

          for (File file: getListOfFiles()) {

               publish(file.getName); //passes the name of the file to process()

               scanFile(file); //just an example method

               fileCount++;

           }

           return fileCount; //can be retrieved by calling get()

     }

 

     //runs on EDT, allowed to update gui

     protected void process(String fileName) {

            //receives the name of the file from publish() and sets it on the textfield.

           textField.setText("scanning file: " + fileName);

     }

 

     //runs on EDT, allowed to update gui

     protected void done() {

           try {

                Integer fileCount = get(); //get() retrieves the return value from doInBackground()

                textField.setText("scan complete " + fileCount + " files scanned");

           } catch (Exception e) {

                //this is where you handle any exceptions that occurred in the

                //doInBackground() method

           }

      }

}.execute();

 

 

Hopefully the example above makes sense and can be used as a guide to help you implement your own solutions using the SwingWorker. I find the SwingWorker to be one of the most valuable tools in my swing toolset. It is fantastic for acting as a building block for complex swing frameworks.

 

Never try reuse a SwingWorker.

Never ever try and reuse a SwingWorker, you should create a new instance every time one is required. This is mentioned in the API, however its not very well published. If you attempt to reuse an existing SwingWorker, the doInBackground() method will not be called.

 

Java 6 Release 18 and the SwingWorker.

I have been working with the SwingWorker successfully since it was originally released in java 5. However there is a defect affecting the SwingWorker in Java 6 Release 18, which effectively brought a critical production system to its knees. The problem manifested in Java restricted the number of SwingWorkers that could be created. After launching a number of SwingWorkers, their thread pool reached capacity and no more workers could be created. The application became unresponsive as it needed SwingWorkers to fetch its required, however no new Workers could be created.

 

Even though this problem was extremely serious, the workaround is very simplistic. Instead of calling the execute() method on the SwingWorker, simply pass the SwingWorker to your own Executor.

 

executor.execute(swingWorker);

 

 

долгая разлука секс видео - Дети

долгая разлука секс видео Предполагается, что материнский организм так реагирует на гормональную перестройку, которая наиболее бурно идет именно в начале беременности. Некоторые специалисты склонны объяснять его появление иммунологической несовместимостью матери и ребенка, что особенно чувствуется в первом триместре. Затем с увеличением срока беременности материнский организм постепенно привыкает к находящемуся в ней «другому» человеку, и неприятные ощущения полностью пропадают. От токсикоза страдает не только женщина, но и маленький человек внутри. секс после долгой разлуки видео Признаки и последствия. секс после долгой разлуки порно Ранний токсикоз обычно возникает в первые 12 недель беременности. Он проявляется угнетенным состоянием, плохим самочувствием, ощущением тошноты, иногда слюнотечением. Несколько раз в день бывает рвота; при этом отмечают слабость, раздражительность, сонливость, снижение веса, так как рвота вызывает обезвоживание организма и резкое похудание беременной. Но от этого страдает не только женщина, но и маленький человек внутри: приток к плоду питательных веществ резко нарушается. В некоторых случаях при чрезмерной рвоте необходима госпитализации – это уже вопрос не только сохранения беременности, но жизни матери! Существует такое понятие, как «поздний токсикоз, так называемый гестоз. Если до 20-недельного рубежа неприятные проявления вас не оставили, дело серьезное. Нужно обращаться ко врачу! https://bubblemom.ru - Беременность, роды, мама и дети. Календарь беременности по неделям Средства борьбы с токсикозом.

executor and swingworker?

Hey, yes, this article is helping me!

THanks for sharing the ideas. Anyway, I still have a problem regarding this SwingWorker. Let say, If i want to do some flipping next frame using cardlayout should I use the SwingWorker to handle this kind of action also?

And one more thing... What about the pool that every instance of the SwingWorker we newly created? Is it safe to always creating them? Because at sometimes after N times it occured to me that the SwingWorker is only limited to such a 10 numbers. And sometimes, the exceptions also occured. Perhaps some of the workers didnt' work as properly. Do you have any suggestion regarding this matter?

 

thanks in advance!

Please Read here Java Multi

The LATEST chatter

  • Halted all development on the twitter client. The application in its incomplete state is available at: http://tinyurl.com/6ktd8xw 8 years 4 weeks ago
  • Java Swing Components is currently undergoing a rebranding exercise to Custom Swing Components. The url however will remain the same. 8 years 27 weeks ago
  • Java Swing Components is proud to announce the release of our rater component. http://www.javaswingcomponents.com/product/rater 8 years 28 weeks ago
  • Java Swing Components is proud to announce the release of our first bundle including a fun demo. http://www.javaswingcomponents.com/products 8 years 32 weeks ago
  • New post: New Component Teaser http://tinyurl.com/35hxfnn 8 years 33 weeks ago

User login

Syndicate

Syndicate content