-
multi-threading problem
I currently have a piece of code that looks like this in pseudo-code:
Code:
ArrayList<Foo> fooList=new ArrayList<Foo>();
while(I need to add more Foo)
{
//make preperations for creating the next Foo
[COLOR="Red"]Foo temp=new Foo(add prepared data into the contructor of Foo);[/COLOR]
fooList.add(temp);
}
return fooList; when fooList is complete
The constructor of Foo needs a relatively large amount of time, because of the networking it does. Since I make a lot of Foo, I want to put the red-line into a seperate thread. That way, when one contructor is waiting on getting a response from another server, another Foo constructor can do some work. However I don't want to return untill the list is complete.
Can anyone give me some pointers to solve this problem?
-
I would try to move the network activity outside the constructor of Foo. But if that's not possible, you could do something like this (exception handling omitted):
Code:
ArrayList<Foo> fooList=new ArrayList<Foo>();
ArrayList<Thread> tList=new ArrayList<Thread>();
while(I need to add more Foo)
{
//make preperations for creating the next Foo
Thread t = new Thread() {
public void run() {
Foo temp=new Foo(add prepared data into the contructor of Foo);
fooList.add(temp);
}
};
t.start();
tList.add(t);
}
for(Thread t : tList) {
t.join();
}
return fooList; when fooList is complete
You might have to make fooList final to access it from an inner class. I forget the rules about that.