Reputation: 63
MainThread has a HashTable, which save a mapping from customId to SubThread Object, and put task to map. SubThread remove task from map. how to avoiding this problem?
thread 1:
public void start()
{
subThreadMap = new Hashtable<Integer, SubThread>();
while(true)
{
List<CloudPusherTaskInfo> taskInfos = TestDao.getTasks();
for (CloudPusherTaskInfo task : taskInfos)
{
distribute(task);
}
}
}
private void distribute(CloudPusherTaskInfo task)
{
SubThread subThread = null;
if(subThreadMap.containsKey(task.getCustomerId()))
{
/*
* if subThread exist, add a task to it
*/
subThread = subThreadMap.get(task.getCustomerId());
/* -----at this point, the other subThread maybe end, and return null--------*/
subThread.add(task);
}
else
{
/*
* if subThread is not exist, create a new subthread, then add a task and run it
*/
SubThread newThread = createNewSubThread(task.getCustomerId());
subThread = subThreadMap.put(task.getCustomerId(), newThread);
newThread.add(task);
new Thread(newThread).start();
}
}
Upvotes: 0
Views: 210
Reputation: 612
The HashTable Hashtable<Integer, SubThread>();
is not needed if its primary reason is to get Thread objects and start them. Make the CloudPusherTaskInfo implement the Runnable interface and then use the Executor.execute(new CloudPusherTaskInfo())
. Or you could hold the CloudPusherTaskInfo tasks in a List and execute them one after another.
Upvotes: 1
Reputation: 86774
If I understand you correctly, it is possible for the subThread to have finished its tasks and ended between the call to subThreadMap.containsKey()
and subThreadMap.get()
.
Don't reinvent the wheel. You should look at the classes in package java.util.concurrent
, which provides all the functionality you need to accomplish thread pooling and task execution.
Upvotes: 2