Home arrow static arrow Java Programming [Archive] - Threaded methods
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Threaded methods
This topic has 11 replies on 1 page.

Registered: 7/2/04
Threaded methods  
Jul 3, 2004 3:54 AM

What if I have a class with a pair (or more) of methods, like this for example:

public class Dummy {   public int methodOne() {      //Perform calculations, return an integer   }    public DummyAgain methodTwo() {      //Process, return a DummyAgain object   }}

How can I make the methods run in a thread separate from the application main thread when called, and still be able to extract the returned values? I'm kind of stuck on this. Any help would be appreciated.

My general question is based on the intuitive feeling that it should be possible to define a class such that some or all it's methods (including constructors) are run in a separate thread. That is, I do not want a single run method that executes once and then kills the thread, but instead I want the individual methods to execute in a (possibly persistent) separate thread every time I call them. Is this possible? And if it's not, what's the bes t workaround? Or is my idea of the whole thing wrong from the beginning?

Registered: 2/15/99
Re: Threaded methods  
Jul 3, 2004 6:13 AM (reply 1 of 11)

Are you confusing function calls and threads? I've seen people do that.

You want to call a function, which performs calculations, and returns a value to the waiting main thread? That's not threading, that's a function call.

So do you want to (1) perform a calculation and get a result back (= function call) or (2) do several things simultaneously (= threading)? What is your main thread going to be doing while the calculation is being processed? There are valid reasons for doing processing in a background thread, e.g. to allow a GUI thread to continue.

Registered: 7/2/04
Re: Threaded methods  
Jul 3, 2004 6:21 AM (reply 2 of 11)

I don't think I'm confusing the two concepts, I merely want to combine them.

The main application consists of a GUI that controls the underlying functionality. In this particular case, reading and writing to a persistent storage is what I want done in the background without noticably affecting the user's interactions with the GUI.

In short: I have a class which provides several methods that are used to communicate with the database. I want the more time-consuming ones to be run in a separate thread. Can I somehow create a thread for this purpose, and then "tell" these methods to run in that thread when called?

Registered: 2/15/99
Re: Threaded methods  
Jul 3, 2004 6:33 AM (reply 3 of 11)

Okey, GUI stuff. Here's a quickie:
    (new Thread() {        public void run() {            doSomethingThatTakesALongTime();        }    }).start();

That doesn't "return" anything to the main thread. The main thread has already gone its way. What you could do is pop up a window after the processing is done, or append "save done" to an existing message window. Whether you are allowed to modify GUI components from a background thread depends on the GUI library.

If you are using Swing: Swing books and tutorials should cover invokeLater() and other Swing threading issues. Here's a quick start: http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html

Registered: 3/8/01
Re: Threaded methods  
Jul 3, 2004 6:34 AM (reply 4 of 11)

Why not just start a separate thread for each method? The threads will be destroyed automatically when their run methods finish. Just use new Thread(new Runnable(){public void run(){yourMethodCall();}).start().

If you really want just one thread, keep a queue of Runnables and make this thread repeatedly look for new items in the queue, and them in order (within itself, just runnable.run()) or sleep a bit if there are no items.

Registered: 7/2/04
Re: Threaded methods  
Jul 3, 2004 10:02 AM (reply 5 of 11)

That's all good, but what if I NEED to get returned values from the method that runs in it's own thread? For instance, suppose I have such a method that takes some criteria as argument, searches the database (in the background) and returns the result when it is done?

Registered: 4/30/99
Re: Threaded methods  
Jul 3, 2004 11:41 AM (reply 6 of 11)

Then you have to wait until it is done.

There are a couple of ways to do this. One is to simply call the thread's join() method. This will wait until the thread ends. Once that happens, you can call the thread's method that you wrote to get its result. If you don't want your main thread to wait, but just to check periodically, you can call the version of join() that only waits for a limited time. There are more complicated scenarios but I don't think you need to get into those just yet.

Registered: 2/25/04
Re: Threaded methods  
Jul 3, 2004 11:52 AM (reply 7 of 11)

So you have one sequence of operations, a method that searches the database, then you do something with the result. You want to use threads so your application can also do something else at the same time.

So have one thread that executes the method call and processes the results, and other thread or threads that do the something else.

If you're triggering the method in a GUI event handler, then start a new thread with both the method call and the processing, otherwise use the main thread for that path an a second thread for the other stuff.



Registered: 7/2/04
Re: Threaded methods  
Jul 3, 2004 12:18 PM (reply 8 of 11)

Okay, I'll try to figure out the best solution for this case. I guess I'm just a bit frustrated that my intuitive idea of threads is not exactly aligned with reality, but that's life.

Thanks for your tips!

Registered: 9/8/98
Re: Threaded methods  
Jul 3, 2004 2:28 PM (reply 9 of 11)

If you want to hear the result of a thread executing a method on
you behalf then you either wait for it (as mentioned earlier) or
register some class as a listener to the thread.

Its hard to explain how this will work in your situation as there is
not enough information in your question. However in general
terms it goes somthing like this.

This is a class used to implement threaded calls to your
method. (this can be done as an anonymous class as shown
earlier in this thread but is done here explicitly for clarity)

class ExecMethodOne implements Runable {     private CallbackListener listener;     public ExecMethodOne(CallbackListener listener) {          this.listener = listener;     }      public void run() throws Exception {            // call your method            Object result = execMethodOne();            // call the notify method on the listener            listener.notify(result);      }}

The CallbackListener interface is as follows:
public interface CallbackListener {        // this method is called by the work thread to notify me        // of the results of its execution. The result Object is the         // result. Make it whatever type you require       public void notify(Object result);}

Then your calling class will to the follwoing

private Object result; public void callmethod {      // implement a simple CallbackListener that updates     // the internal result variable.     final CallbackListener cbl = new CallbackListener() {           public void notify(Object o) {                 result = o;                 // note that this method is called on the same                 // thread as the background wiki/./method is executing on.           }     }      // create a new thread, register the listener and start it       // running.     new Thread(new ExecMethodOne(cbl)).start());}

This allows you to be notified of the result of your method call without waiting for the method to complete. How you handle
the change in value of the varaible in your calling class is up
to you and highly dependent on what you want to achieve.


Registered: 7/2/04
Re: Threaded methods  
Jul 4, 2004 3:01 AM (reply 10 of 11)

That's a very useful answer! Thanks a lot!

Registered: 7/6/04
Re: Threaded methods  
Jul 9, 2004 1:32 AM (reply 11 of 11)


can this call back system be applied to database queries?

I want to build a queue that will be consumed by a worker thread and each object that is popped will be ran on such a callback method i.e if the query is a success then a true flag is returned and if there is a problem a false flag will be returned....

Any suggestions on how I could implement this?

This topic has 11 replies on 1 page.