Future.get and the event despatch thread blocking

neeeyaaarghhhh
been tying myself in knots thinking about this
Following one of the java tech tips I've been using Callable and Future objects when I want to return a result from a task, in my case it's usually some file processing
So I have a file chooser gui, I select a file and launch my Callable and await the result in Future.get...
Now the problem is... Future.get I understand blocks the calling thread until the computation / work in the Callable is done and the result returned. In this case the blocked thread will be the event despatch thread... which causes problems as during my file reading I have a JProgressBar running and updating. Well at least I did, now it doesn't show up at all as all the updates to the JProgressBar via invokeLater are queued (as event despatch thread is blocked) until after the work thread has finished
How do I launch a Callable, await the result and have some limited gui activity as the task progresses? The only solution I've found is to have the ProgressBar in a modal dialog, to block out the rest of the gui like this whilst I do the work in the event despatch thread (and drop the idea of threading altogether)
Is my mental modal of how worker threads should spin off from the event thread flawed or am I just missing some 1 line command?

In the situation of updating the gui, you usually want to pass some sort of callback object to the asynchronous code and have that callback method run on the gui event thread.
public class GuiClass {
public void handleResult(Object data);
public void startTask() {
  threadpool.execute(new Runnable() {
    public void run() {
      // ... do asynch work ...
      final Object myResult = ...;
      SwingUtilities.invokeLater(new Runnable() {
        public void run() {
          handleResult(myResult);
}In this code, the startTask method is called on the gui thread. it starts some async work on the threadpool. when finished, the asynch task queues the result to be handled back on the gui thread. the handleResult method is called later on the gui thread with the final result. thus, no blocking of the gui thread.
The Callable interface is great for when the invoking thread needs to wait for a result, but you pretty much never want to do this with the gui thread.

Similar Messages

  • Flags and the Event Thread

    I was writing code for a game and I realized that the AWT event thread could change the value of a flag while I'm in the process of updating the game state. This can cause a few problems, or it could even leave events not handled because of it. I see code like this all the time as a fix to the threading issues, am I missing something or is it really a solution? I can't post the actual code as it's too long, so I created a simple example:
    import java.awt.event.*;
    import javax.swing.*;
    public class EventTest extends JFrame implements KeyListener, Runnable
         private boolean isKeyDown;
         public EventTest()
              setSize(500, 500);
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              setVisible(true);
              addKeyListener(this);
              new Thread(this).start();
         public void keyPressed(KeyEvent event)
              //synchronized(this)
                   isKeyDown = true;
         public void keyReleased(KeyEvent event)
              //synchronized(this)
                   isKeyDown = false;
         public void keyTyped(KeyEvent event) {}
         public void run()
              // game loop
              while(true)
                   //synchronized(this)
                        boolean cache = isKeyDown;
                        System.out.print(isKeyDown); // before
                        System.out.print(' ');
                        /* event handling, game logic, etc. done here
                           do some useless operation to simulate this */
                        long time = System.currentTimeMillis();
                        while(time + 1 > System.currentTimeMillis());
                        System.out.println(isKeyDown); // after
                        if(cache != isKeyDown)
                             System.out.println("PROBLEM!");
                        // render everything to the screen
                   try
                        Thread.sleep(100);
                   } catch(InterruptedException e) {}
         public static void main(String[] args)
              new EventTest();
    }Basically I have a game loop, where I update the game state, handle events, then draw things to the screen. Each time a key is pressed or released, I set the appropriate value to isKeyDown from the AWT event thread. The desirable output is to have the booleans equal to each other so that "false false" or "true true" is printed out on the screen constantly, but once in a while I'll get a "false true" or "true false", which is expected but obviously not wanted.
    So one solution is right there commented out (synchronizing), though most people seem to avoid it. I see everybody using flags like this, so I'm wondering if I'm missing some obvious solution to the problem or if it's really even that big of a deal. I don't see any other fix, but that's why you're all here. ;)
    Thanks.

    Swing related questions should be posted in the Swing forum.
    I converted your simple example to use a Swing Timer instead of a while(true) loop with a Thread.sleep. I experienced no problems as expected since all the code will be executed in the Event Dispatch Thread (EDT).
    Of course using this approach could make the game less responsive if your game logic is extensive and hogs the EDT, but given that you try to invoke your game logic every 100 millisecond I assume it can't be that extensive.
    Anyway here is the code I used as a test:
    import java.awt.event.*;
    import javax.swing.*;
    public class EventTest extends JFrame implements KeyListener, ActionListener
         private boolean isKeyDown;
         public EventTest()
              setSize(500, 500);
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              setVisible(true);
              addKeyListener(this);
              new Timer(100, this).start();
         public void keyPressed(KeyEvent event)
              isKeyDown = true;
         public void keyReleased(KeyEvent event)
              isKeyDown = false;
         public void keyTyped(KeyEvent event) {}
         public void actionPerformed(ActionEvent e)
              boolean cache = isKeyDown;
              System.out.print(isKeyDown); // before
              System.out.print(' ');
              /* event handling, game logic, etc. done here
                 do some useless operation to simulate this */
              long time = System.currentTimeMillis();
              while(time + 1 > System.currentTimeMillis());
              System.out.println(isKeyDown); // after
              if(cache != isKeyDown)
                   System.out.println("PROBLEM!");
         public static void main(String[] args)
              new EventTest();
    }

  • ..this method should be invoked from the event-dispatching thread?

    I see this (the title that is) in every single Java demo/example program on this (Sun's) site. However, I just tend to
    public static void main(String[] args){
       new whateverTheClassIsCalled();
    }And I've seen this approach on other sites and other example programs.
    So what exactly is better about this;
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        }where createAndShowGUI() sets and packs the frame. I just do all this in the class constructor (when it's a JFrame!)
    So what does all this thread dispatching stuff mean, why should I use it etc etc.
    tia.

    Is it just me? For some reason it rubs me the wrong way that swing isn't thread safe. From what I've read, my understanding is that its safe to modify swing components from other threads as long as they haven't asked to be painted. If you don't do paint(), pack() or setVisible(true) until the end of your initialization, you will be safe.
    The reason for not being thread safe is almost certainly performance. Swing is slow enough as it is. Since the vast majority of Swing activity takes place in response to events and thus is on the EDT, there usually isn't a problem.
    This is a serious nuisance in network and database programs where multiple threads are used. I end up using invokeLater a lot in those cases, but never for initialization. Sun has only started to recomment that recently.
    Note that the fireXXX methods do not put the event on the EDT, these simply create Event objects and send them to Listeners. If they are executed off the EDT the Listeners will get called off the EDT.

  • Executing Code outside of the Event Dispatcher Thread

    Hello,
    I have just come to learn that any actionPerformed() method that is called after an event occurs actually runs in the Event Dispatcher. So, for example, if you click on a button, any code that is run as a result is run in the event dispatcher.
    So there are two things I am wondering about. First, If i run code in response to a user event, then it doesn't have to use invokeLater() to update GUI components because it's already being run in the event thread? Second, if I run code in response to an event but it's computationally expensive and I do not want to run it in the Event Dispatcher thread, how do i do that? Will a method call cause it to do so, or do i have to specifically create a new thread for it?
    My questions are a result of this: How does one normally go about updating a GUI during a long process? I figured that if I could get the process to run in any thread other than the Event Dispatcher, I could call invokeLater() within it and it would update the GUI. Am I correct in assuming so?

    So there are two things I am wondering about. First, If i run code in response to a user event, then it doesn't have to use invokeLater() to update GUI components because it's already being run in the event thread?
    Correct. So if your response to an action is, for example, creating a new bit of UI using data which is already in memory, you can just do it.
    Second, if I run code in response to an event but it's computationally expensive and I do not want to run it in the Event Dispatcher thread, how do i do that? Will a method call cause it to do so, or do i have to specifically create a new thread for it?
    You will need to create a new thread: method calls are just control flow within the same thread.
    You should use an object which implements Runnable and then use "new Thread(foo).start()"
    My questions are a result of this: How does one normally go about updating a GUI during a long process?
    You have to hop back onto the EDT whenever an update is required. I'd suggest writing yourself a little reusable class or two to help you with this - such as a listener mechanism with an implementation which handles the thread hopping.
    I figured that if I could get the process to run in any thread other than the Event Dispatcher, I could call invokeLater() within it and it would update the GUI. Am I correct in assuming so?
    Yes.
    Should I use inner classes? I would prefer to keep them as separate classes within the same package.
    Depends on all sorts of things - sometimes anonymous or declared inner objects are the way forward, sometimes public class objects, sometimes generic helper objects and sometimes utility classes. There are all sorts of different scenarios. As I say, though, it's worth writing some utility/helper classes to reuse. Personally I don't find SwingWorker is ideal so I have my own. Note that an abstract Action implementation is a very useful one, since this is precisely where you need to be doing most of the thread hopping.

  • Not Running on the Event Dispatch thread, but UI still freezes

    The environment: I am currently working on an application that requires some heavy lifting in response to user input on a UI. To do this I am using a version of SwingWorker that was backported from java 1.6 to java 1.5 in conjunction with a slew of custom threads.
    The problem: I am currently running into an issue where I am not operating on the Event Dispatch thread (checked by doing a javax.swing.SwingUtilities.isEventDispatchThread()) but the UI is still freezing during this section. The operation involves a loop with about 2000 iterations and contains several file accesses. I have thought about how to make a new thread to perform the same operation, but I do not see how it would be any different since as it is I am not on the EDT. The call is being made from doInBackground and specifically the piece that is slowing things down is the File Accesses (2 for every iteration of the loop). At this point I am not sure how to go about resolving the issue. Any one have any suggestions?

    I am not operating on the Event Dispatch threadThat is the problem. Use multiple threads for GUI, which should delegates to the EDT, and your app logic.

  • I'm trying to use global keys hooking but why it's never get to the events ?

    I created a new class and added this:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    namespace Capture
    class Hook_Keys
    globalKeyboardHook gkh = new globalKeyboardHook();
    public bool onoff = false;
    public Hook_Keys()
    gkh.HookedKeys.Add(Keys.A);
    gkh.HookedKeys.Add(Keys.B);
    gkh.KeyUp += new KeyEventHandler(gkh_KeyUp);
    gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
    void gkh_KeyUp(object sender, KeyEventArgs e)
    onoff = true;
    e.Handled = true;
    void gkh_KeyDown(object sender, KeyEventArgs e)
    onoff = false;
    e.Handled = true;
    Then in another class top i added:
    Hook_Keys hookeys = new Hook_Keys();
    And then using it like this:
    if (hookeys.onoff == true)
    font.DrawText(null, String.Format("{0:N0} fps", this.FPS.GetFPS()), 5, 5, SharpDX.Color.Red);
    string timeRunning = FramesPerSecond.RunTime.ToString();
    font.DrawText(null, String.Format("{0:N0} time running ", timeRunning), 5, 30, SharpDX.Color.Red);
    But when i click on A or B i used a breakpoint it's never get in to the events gkh_KeyUp and gkh_KeyDown 
    I used a breakpoint and it does doing the constructor the public Hook_Keys() part.
    But never get to the events.
    I took the code from here:
    Global Key Hook
    What i want to do is either clicking on A or B one of them will change the bool variable to true and the other key to false.

    Try to add the below in your form constructor:
    public Form1()
    InitializeComponent();
    KeyPreview = true;
    Fouad Roumieh

  • Why don't my photos appear as they do in iPhoto on my Apple Computer. Even though I specify to sync all Events, Faces, etc. the iPad 2 is missing Faces categories and the Events are in a different order.

    Why don't my photos appear as they do in iPhoto on my Apple Computer. Even though I specify to sync all Events, Faces, etc. the iPad 2 is missing Faces categories and the Events are in a different order.

    1) The best way to relocate the iTunes library folder is to move the entire iTunes folder with all subfolders to the new path, then press and hold down shift as start iTunes and keep holding until prompted to choose a library, then browse to the relocated folder and open the file iTunes Library.itl inside it.
    If you've done something different then provide some more details about what is where and I should be able to help.
    2) Purchases on the device should automatically transfer to a Purchased on <DeviceName> playlist, but it my depend a bit on whether automatic iCloud downloads are enabled. If there is a cloudy link then the transfer might not happen. You can use File > Devices > Transfer Purchases. In iTunes you should also check out iTunes Store > Quick Links > Purchased > Music > Not on this computer.
    3) Backup the device, then immediately restore it. In some cases you need to add a restore as new device into that equation. Obbviously not to be attempted until you're sure all your media is in your library. See Recover your iTunes library from your iPod or iOS device should it be needed.
    4) I believe there is complimentary 1 incident 90-day support with hardware purchases, but no free software support for iTunes itself. AppleCare gets you a different level of support.
    tt2

  • I can't text a contact but can voice phone them. I don't have the problem with any other contact and the contact is not blocked. I have an iphone5.0 OS 8.1.3

    I can't text a contact but can voice phone them. I don't have the problem with any other contact and the contact is not blocked. I have an iphone5.0 OS 8.1.3. I used to be able to text them with no problem. The only difference I can think is that this problem may have started since I downloaded the OS I am using now
    cycleluke

    Wasn't responding to you. Please show me links where this helped.
    Apple isn't showing any system problems: https://www.apple.com/support/systemstatus/

  • How can I archive photos in iPhoto to a hard drive and retain the Album folders and the Events?

    How can I archive photos in iPhoto to a hard drive and retain the Album folders and the Events?  I tried to Export the Albums but just transferred the files individually.

    If you want to maintain the iPhoto organisation then back up the iPhoto Library.
    If you want to export to the Finder, well you need to create a folder for the contents of an Album and expot to that.
    If you have an older version of iPhoto: Apps like iPhoto2Disk or PhotoShare will help you export to a Folder tree matching your Events. This feature is built in to iPhoto 11.
    This User Tip
    https://discussions.apple.com/docs/DOC-4921
    has details of the options in the Export dialogue.

  • Future versions and the relese dates

    Can anybody give the Oracle planning about the Future versions and the release dates of the versions.
    Becaz Oracle support mentioned some of problems which we were facing in Oracle Streams will be addressed in Future Major releases. If we know the release dates of the future releases we can plan in our project wether to use the STREAMS or not.
    Thanks & Regards
    Rajesh

    The next version of Portal Server will fully support Portlet 2.0 (JSR-286) spec.
    The implementation is expected to be released as soon as the spec is done (it is Public Draft now)
    A sneak preview of Portlet Container 2.0 based on public draft will be
    also available as part of upcoming Java Application Platform SDK.

  • My magic trackpad fell yestarday and the start button appeared blocked and now it does not work. Apple is not competent in giving a solution. Only replacement is possible paying a new one. They simply do not repair it. Anyone may help me with a solution?

    My magic trackpad fell yestarday and the switch button appeared blocked and it is not possible to make it working. I contacted Apple support and it is not competent in giving a solution. They only suggest replacement and pay a new one. They simply do not repair it. It is a very poor solution since there would be other solutions. Anyone may help me with a solution?

    Hello folks!!!. I found out a solution. I simply take the start button off with a screwdriver and now the trackpad works properly. Since it initializes automatically when the computer turns on, the magic trackpad works without the need of using the start button. The only drawback is that there is a loss of aesthetic because the trackpad has now a gap, which was occupied by the button, but it is not easy to notice. It seems to be a better solution than that given by the apple customer service, which was to pay a new one.

  • JTAPI Getting all the events of all calls

    Hello, colleagues. Could you be so kind to help me with the following problem: what Observer will give me the ability to track all events (for Cisco UCM)? I've seen somewhere that it is possible, and even there it is possible to set what to filter. The goal is to catch the event FORWADRNOANSWER, then track how the connection is closed on the second leg. I dont want to put CallObserver on all terminals or address, and I am not sure it is possible...
    Also the second leg which is created due to FORWADRNOANSWER terminal or address is not visible.

    Hi ,
    Use framepositioningcontrol to check total frames and with seek you can grab a single frame
    greetz Sven
    public void takeSnapShot() {
        try {
    //      Control[] controls = player.getControls();
          FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl(
              "javax.media.control.FrameGrabbingControl");
          if (fgc != null) {
            Buffer buf = fgc.grabFrame();
            javax.media.util.BufferToImage bti = new javax.media.util.BufferToImage( (
                VideoFormat) buf.getFormat());
            if (buf != null) {
              try {
                Image image = bti.createImage(buf);
                ImageDisplayer f = new ImageDisplayer(image, this.recources,
                                                      this.images);
                f.setDirectory (directory);
                f.setSize();
                f.setVisible(true);
              catch (Exception imex) {
        catch (Exception ex) {
          System.out.println("Error in snapshot module in videowindow");
      }

  • Since latest IOS7 update my phone is getting and the battery is depleted very quickly

    Has anyone noticed thier phones overheating and battery direing since the new IOS7 update in Feb 2014?

    There have been some reports of unusual battery use after the iOS 7.0.6 update. A report that I saw on my Xite newsreader indicates users have found that quitting all apps and then resetting the device will correct the problem.
    Double click the Home button to show the screen with running and recently used apps. Each app icon will have a sample page above it. Flick up on the page (not the app icon) and the page will fly away and the app icon will disappear. This quits that app. Do this for all apps shown in the recently used apps area. Then reset your device. Press and hold the Home and Sleep buttons simultaneously until the Apple logo appears. Let go of the buttons and let the device restart. See if that fixes your problem.

  • Error display the date in the calendar and the event is lost in the list of the day

    At one point written on November 2, in another November 3 in the list for the day and 2 and 3 of this event no!

    Hi,
    Try this code.
    TYPES: BEGIN OF type_t_date,
    mm(2) TYPE c,
    filler1(1) TYPE c,
    dd(2) TYPE c,
    filler2(1) TYPE c,
    yyyy(4) TYPE c,
    END OF type_t_date.
    DATA: t_ddate TYPE type_t_date.
    CONSTANTS: c_fil TYPE c VALUE '.'.
    t_ddate-mm = rs_sdate-mm.
    t_ddate-dd = rs_sdate-dd.
    t_ddate-yyyy = rs_sdate-yyyy.
    t_ddate-filler1 = c_fil.
    t_ddate-filler2 = c_fil.
    CONCATENATE t_ddate-mm t_ddate-filler1 t_ddate-dd t_ddate-filler2 t_ddate-yyyy INTO rv_ddate.
    Regards,
    Amit

  • Just reinstalled lightroom 5 from CC and the develop module is blocked and says I need to renew membership although I have an up to date photographers CC membership with photoshop CC and lightroom 5 - is there a simple way to reactivate the develop module

    Does anyone know how to reactivate the develop module in Lightroom 5- I've just reinstalled it, restarted computer, signed in but keep getting the message  - Develop module is disabled - Renew membership - although my CC membership is all up to date. I can import to the library etc just seems to be the Develop module- thanks for any help, T

    Solution posted here
    Re: Lightroom 5.5 "Develop Module Disabled, please renew your membership"

Maybe you are looking for

  • LiveUpdate 6-not running after last update

    application not running after start win7x64, but I did not set anything and not even start pls. test application main PC: moth. H97 CPU: Corei-5 VGA: GTX 560Ti thx

  • Panic Attacks

    Hi out there, this is my first posting, hope someone can help. I've been experiencing system hangups and kernel panics for a couple of months now. I upgraded to Tiger, so I could use my i=pod!, and added an additional 512 mb of RAM at the same time (

  • How to get af:column in the bean using findComponent

    Hi I am getting null if I find the component using id in the bean. The component does exist in the JSP though. Can someone tell me how it can be done please? I am trying to set the header text in the bean. <af:panelCollection id="pc1" inlineStyle="wi

  • Acro 9 Pro Ext hyperlinks and attachments

    Hi, This is an odd one. I have a PDF that was created by MS Publisher 2008. The PDF document has hyperlinks that were created in original Publisher doc. If I open the PDF the hyperlinks (pointing to pages within the document) work OK. However, when I

  • Any way to seperate duplicates so both aren't deleted

    I have loaded a lot of duplicates and when you display them how can you delete just one of the duplicate so you still have one left? ie two of the same song if you highlight or delete all you don't have a copy left. It is further complicated by the f