Taming Swing Threads Part 2: Common Event Queue Pitfalls

Key points from part 1.

Hopefully after reading part 1 you should be feeling pretty comfortable about what the EDT is and how it processes, but just as a reminder, here are the key points from part 1.

  • Only the EDT may safely manipulate swing components (it is the uber master swing thread).
  • If any other threads are manipulating swing components, they are doing so in an unsafe manner (and bad things will happen).
  • The EDT processes events using a simple sequential queue called the Event Queue.

 

The idea behind part 2 is to explain some of the tricky situations and pitfalls that swing developers often get caught in, as well as hopefully answering some of the questions you have regarding the Event Queue.

Someone jumped the queue!

Every now and then it appears that some swing events are processed in the incorrect order in the Event Queue (and nothing gets my blood boiling like when someone cuts into a queue) resulting in strange behavior. This is best illustrated with a small code snippet. Read the snippet below and think carefully in what order you imagine events will take place.

 

button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

             repaint();

             doSomething();

        }

});

 

Most developers would image that repaint() method will result in a painting operation taking place before the doSomething() method call. However this is actually not the case, the call to repaint() will create a new paint event that will be added to the end of the Event Queue. This new paint event will only be processed (dispatched) after the current Action Event has completed. This means that the doSomething() method will be executed before the new Paint Event on the queue is dispatched.

 

 

The key point here is that calls to repaint() will create a new paint event that will be added to the end Event Queue and not processed immediately. This means that no events jump the queue (and my blood can remain at its correct temperature).

 

This queue is going nowhere.

A question I have been asked on numerous occasions is “if all swing interaction can only safely occur on the EDT, why not perform all our tasks on the EDT?”. This is a great question and leads me on to the next common pitfall in swing, problems with long running tasks.

 

As we discussed earlier, the Event Queue processes all swing interactions: be it painting, mouse clicks or key capture, in a sequential manner. If your code executes quickly, all your screen interactions will be fast and your user interface will feel zippy. However problems arise when long running code is executed by an event.

 

Common examples of long running tasks include:

  • Reading a large file from a drive.
  • Performing complex calculations.
  • Communicating with data sources or remote machines.

 

Remember that any operation you perform in an Action Event or other similar events will be completely processed on the EDT, before any other events will be processed These long running tasks will be added to the Event Queue, but will prevent any painting events (or other events) from occurring until the long running task is complete. The result of this is that the GUI becomes unresponsive, as no paint events are being processed.

 

Below is a simple code snippet that illustrates this problem. The code enters a loop during which it must perform a very long running task.

 

button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

             for (int counter=0; counter!=3; counter++) {

                        doVeryLongTask();

             }

        }

});

 

 

Upon noticing that their GUI is no longer responsive and that painting is not occurring, most new developers try to add a repaint() event in the Action Event to try get the screen to repaint. However we know  that calling repaint() will create a new paint event, but it will only be processed after the Action Event, hence this solution does not work.

 

button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

             for (int counter=0; counter!=3; counter++) {

                        doVeryLongTask();

                        repaint();

             }

        }

});

 

 

The key point to take away from this example is that in order to keep your swing application responsive, you must not perform any long running tasks in the EDT, as the long running event will block the Event Queue and no painting will take place until its finished.

 

So how on earth do I execute long running tasks?

We have learnt so far that in order to keep you application responsive, you should not perform long running tasks in the EDT that block the Event Queue. This makes total sense, but begs the question “where should long running tasks be executed”. The answer to this question is to perform your processing in another background thread; however this answer opens up an entirely new can of worms.

 

The following code snippet is the perfect example of what not to do, give it a read and see if you can spot the problem:

 

button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

                new Thread(new Runnable() {

            public void run() {

                    String answer = calcSomethingComplex();

                    textField.setText(answer);

            }

                }).start();

        }

});

 

If you cast your mind back to the start of the article you hopefully remembered that swing is a single threaded model and that only the EDT is allowed to interact with swing components. This means that in order to be thread safe, your background task will not be allowed to interact with any swing components.

 

In the code above, the developer correctly moved the processing of the long running task to a background thread, however the line textField.setText(answer); is not thread safe as it results in a background thread interacting with a swing component. This code violates the golden rule that only the EDT may interact with a swing component.

 

Help!

So pushing the long running task into a background thread will allow my application to be responsive and zippy, but how on earth do you update the user interface once the long running task is complete?

 

I’m afraid you will have to read part 3 of the blog to find the answer to this problem.

 

HealthyandBeauty.co - Your Healthy and Beauty Source!

Running out of health and beauty essentials used to mean trekking all over town to track everything down. Now, ticking off that shopping list can be done from home. From makeup and perfume, to appliances such as hair dryers and GHD straighteners, HealthyandBeauty.co is the place to go to find it all. Looking to create a new look? While having a makeup routine certainly saves time, it can be fun to try out new looks now and again. Whether it’s dewy and fresh, or full matte coverage, foundation is the base for any new look. Time for some contouring? Use a beauty blender, bronzer and highlighter to add contour and beautiful highlights, accenting great features (and playing down those that are perhaps not so great). Splash of colour? From exquisite neutrals to bold fabulous colour, a new eye shadow palette and quality makeup brush set can create a gorgeous new look with minimal effort. Finish it off with a hint of eyeliner, a coat of mascara and a flash of lipstick or lip gloss, and a whole new look is ready to be unveiled. https://www.HealthyandBeauty.co/

CME Punkte kaufen

Sie haben keine Zeit für lange Fortbildungen? Bei uns erhalten Sie kostengünstig ihre noch fehlenden Fortbildungspunkte in wenigen Minuten. Von Experten erstellte Lernhilfen mit Lösungen. Garantiert echt und anwendbar. www.fortbildungspunkte-kaufen.de Wir bieten ihnen aktuelle Kurse zu vielen Themengebieten kostengünstig zum download an. Einfacher und kostengünstiger können Sie Ihre noch fehlenden Fortbilungspunkte nicht erhalten.

Adult galleries

New sissy girls blog website old man boy porn tube dress in pink halloween pinup http://sissies.purplesphere.in/?post.violet meaning of reactions large size shoes silk dressing gown dutch clothnig store black tops french maid sexy outfit essay on my college all inclusive holidays to crete 2015

luckypatcherdownloads

Lucky Patcher APK v6.7.5 (Latest) Direct Download for Android. Download Lucky Patcher APK Android Application (Latest) File From Here.lucky patcher apk

eather is also an excellent

eather is also an excellent choice because of its high quality. Leather is extremely durable and can outlast most other fabrics. Why pay for an expensive bar stool than can break over time or bend from usage? Leather will stay strong use after use compared to other fabrics used on chairs. Any spills or liquid damage easily washes off from cloths with no stains. Over a decade, you might have to replace these chairs several times from damage, but with leather back chairs, they can survive most accidents and wear and tear. aol mail sign in

Great New

shareit for pc download from here

室內設計‧裝潢統包-木作工程

室內設計‧裝潢統包-木作工程http://interior-plan.com/

windows product keys

Windows 10 Operating System was released in Jiuly 2015. After the release of this software, many changes were made to fix the bugs windows product keys

【捷特團體服】全台北、桃園、新竹最專業的團體服訂做─團體服│班服│系服│制服│工作服│廟服│選舉背心

【捷特團體服】全台北、桃園、新竹最專業的團體服訂做─團體服│班服│系服│制服│工作服│廟服│選舉背心 http://clothes-group.com/

windows product keys

Windows 10 Operating System was released in Jiuly 2015. After the release of this software, many changes were made to fix the bugs windows product keys

shareit apk

shareit app which is used for to share file through wifi so shareit download and install.

shareit apk

shareit app which is used for to share file through wifi so shareit download and install.

Samsung Galaxy Note 8

After the debacle of the Note 7 last year, Samsung is eager to regain the reputation of this coveted series by the upcoming Samsung Note 8. With an improved battery and better specs, Note 8 is going to be a beast of a device. Want to know more about Note 8? Check this website. 

Gmail Account Sign Up and support

To create a gmail account. so, sign up into Gmail Account Sign up

Gmail Account Sign Up and support

New Gmail Account / Gmail.com join / Gmail Account Sign up : When I first have known about you goodness, Gmail regardless I recall. 

A really nice and well

A really nice and well written article by one of the greatest writer in the world!!

ipl 2017 auction

Google

google

showbox apk latest version 4.72

Every movie freak just want to know which app is better for online movies and TV shows streaming after lots of try and searches i personally prefer showbox  apk , not because its latest movies collection even lots of latest features, i think you all should try for best movie experience.
 

Recent site

New launched porn position erotic webcomics erotic tv channel erotic jokes adult cartoons sextoys http://twerking.erolove.in/?mckenna erotic mens underwear bondage erotic christmas sexy chat adult stories

Check my recent devise

My new work is top! amazon app market download rooted android download sexy videos adult google play store for android free download watch online movies app for android http://erotic.apps.android.blogporn.in/?diagram.unique games to download for phone free live tv streaming for android android video player mp4 free live television mobile online price

My contemporary folio

My revitalized time google maps apps for android images photos download 3d live wallpaper for mobile free download downloader for android tablet sexy film freedownload http://sexgames.android.tobuy.in/?diagram.katelin download play store for android apk adult vid giochi applicazioni para descargar retrica mp4 seks video

Reply to comment | Custom Swing Components for the Java™

Thanks for any other magnificent article. The place else could anybody get that type of information in such a perfect approach of writing? I have a presentation next week, and I am on the search for such info.

asdfasd

eather is also an excellent choice because of its high quality. Leather is extremely durable and can outlast most other fabrics. Why pay for an expensive bar stool than can break over time or bend from usage? Leather will stay strong use after use compared to other fabrics used on chairs. Any spills or liquid damage easily washes off from cloths with no stains. Over a decade, you might have to replace these chairs several times from damage, but with leather back chairs, they can survive most accidents and wear and tear. aol mail sign in

Showbox Movies Online

Get trendy movies online only on Showbox movies app.

Showbox Movies Online

Get trendy movies online download showbox movies app.

The LATEST chatter

  • Halted all development on the twitter client. The application in its incomplete state is available at: http://tinyurl.com/6ktd8xw 7 years 48 weeks ago
  • Java Swing Components is currently undergoing a rebranding exercise to Custom Swing Components. The url however will remain the same. 8 years 18 weeks ago
  • Java Swing Components is proud to announce the release of our rater component. http://www.javaswingcomponents.com/product/rater 8 years 19 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 24 weeks ago
  • New post: New Component Teaser http://tinyurl.com/35hxfnn 8 years 24 weeks ago

User login

Syndicate

Syndicate content