Results 1 to 2 of 2
Thread: Thread Wait
- 03-16-2009, 09:05 PM #1
Member
- Join Date
- Mar 2009
- Posts
- 4
- Rep Power
- 0
Thread Wait
The following method creates threads that retrieve the Store objects of connections to an imap server
My problem is that these lines:
store = IMAP.getStore();
storeList.add(store);
run before the thread has reached the stage where it stores the object in the IMAPthread class
How would i get the thread to wait exactly the right amount of time, until the store object gets stored?
Java Code:for (int i = 0;i<=accountsDetails.size()-1;i++) { IMAPthread IMAP = new IMAPthread(); IMAP.setUser(usernames[i]); IMAP.setPass(passwords[i]); Thread t1 = new Thread(IMAP); t1.start(); store = IMAP.getStore(); storeList.add(store); }Java Code:public class IMAPthread implements Runnable { private String theUser; private String thePass; private Store store; public void run() { ImapServer imap = new ImapServer(); imap.setUser(theUser,thePass); imap.connect(); store = imap.getStore(); } public Store getStore() { return store; }
- 03-19-2009, 05:26 PM #2
First, creating a local variable with all capital letters is confusing. Typically, all caps indicates a static final variable (a constant).
You have created a "race" condition in your IMAPThread class. That means there is no way to guarantee the run() method completes before the getStore() method is invoked; it's a race between the two.
You also have a larger problem. Thread creation is very slow. You are using threads to speed up creating connections, but you are losing any value in doing so by creating a thread for each connection. That is also leading to your race condition.
One option is to simply take the hit a start up and get rid of the threads altogether. That makes sense if you are only opening a few connections that will stay open for a long time.
A second option is to create a thread that's job is to create stores, which is the real goal. Have that thread add the stores to the List. The main thread can use whatever stores are currently available while the thread continues to create more. This approach only makes sense if you need to create a large number of stores on a regular basis.
Similar Threads
-
about wait() and notifyALL
By denis in forum Threads and SynchronizationReplies: 13Last Post: 04-22-2009, 08:28 AM -
[SOLVED] Application should wait until a Dialog closes
By hannehomuth in forum Advanced JavaReplies: 2Last Post: 07-24-2008, 02:51 PM -
What is the execution path of wait() and notify() ?
By AegisCruiser in forum Threads and SynchronizationReplies: 1Last Post: 04-23-2008, 06:16 PM -
How to use sleep() to wait for a while
By Java Tip in forum java.langReplies: 0Last Post: 04-09-2008, 06:32 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks