Bosiwow
Bosiwow

Reputation: 2213

Difference between futures and setting inside thread

Today I discovered threads in java. Now I'm at a point where I want the thread to make a change to my gui. I have this two implementations. I don't know if there are any big differences between them. But the first one without futures kinda 'hangs' my program. My gui becomes very unresponsive etc. The second one seems better. Can anyone explain me which one is best and why?

Runnable hasherRunnable = new Runnable() {
        public void run()  {

            notifyObservers(getHasher().hash(input));

        }};

        this.getPool().submit(hasherRunnable,"hasherThread");
    Callable<String> callableHasher=new Callable<String>(){
        public String call(){
            return getHasher().hash(input);
        }
    };
    ============================================================
    Future<String> future = this.getPool().submit(callableHasher);
    try {
        notifyObservers(future.get());
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Upvotes: 0

Views: 108

Answers (1)

dramzy
dramzy

Reputation: 1429

You should not be updating the GUI from any thread other than the Event Dispatch Thread (EDT). To run a runnable on the EDT, use:

EventQueue.invokeLater( new Runnable(){
             @Override
             public void run() {

             }
        });

Swing also has SwingWorkers which are worker threads that you can use to do time-consuming operations off the EDT and get updates back to the GUI. You use them like this:

   new SwingWorker<T,T>(){
        @Override
        public Void doInBackground(){
           return t;  //Object of some type T 
        }

       @Override
       public void done() {
          try {
              T somVariable = get();
              // Use someVariable to update the GUI 
           }
          catch (InterruptedException ignore) {
             // handle exception
          }
          catch (java.util.concurrent.ExecutionException e) {
            // handle exception
          }
       }.execute();

SwingWorkers make it a whole lot easier to deal with futures. For more on these, read the Java tutorials on worker threads.

Upvotes: 3

Related Questions