java如何实现一种以非同步方式处理服务超时的方法?
假设您有一个需要连续检查“服务”时间的流程。我想设计这个过程,以从线程安全列表中删除并记录即将超时的“服务”
有什么好方法可以持续检查“服务”类型的CopyOnWriteArrayList是否超时
- 请记住,其他“系统”可能需要随时将服务添加到列表中。因此,我们必须不断检查将另一个服务添加到列表中的进程的持续时间李>
Consumer(){
//some method that adds service objects to the list."
}
public class Service(){
// time would represent the time it was created by some system.
int time;
// unique id of service.
String id;
}
public class ServiceTimeoutProcesser{
private CopyOnWriteArrayList inputCopyOnWriteArrayList;
private TimetoLive timetoLive;
ExampleProcess(CopyOnWriteArrayList<Service> inputCopyOnWriteArrayList, TimetoLive timetoLive){
this.inputCopyOnWriteArrayList = inputCopyOnWriteArrayList;
this.timetolive = timetolive;
}
//Ultimately I would call this over and over till triggered to stop ....
private void KeepCheckingTime(inputCopyOnWriteArrayList){
for(Service service : inputCopyOnWriteArrayList){
Long currentTime = System.currenttime();
if(service.time - currentTime > timeTolive){
//remove service from list
// logged that you kicked out service
// maybe add service to some other list to be re processed?
}
}
}
一个低效的想法的例子是做一些像
// create some kind of infinite loop
while(true){
//call KeepCheckingTime(inputCopyOnWriteArrayList)
}
// If you think this is a good solution tell me why.
理想情况下,我希望一个线程多次调用这个函数,但是一个线程在执行后会死掉,对吗?导致我无法记录失败的“服务”,如果它在单线程完成执行后被视为过期。我知道可以创建线程池,但与列表的大小相比,我并不总是知道需要启动多少线程。例如,我在线程池中创建了5个线程。。。。。他们执行KeepCheckingTime。如果我的所有线程在任何“服务”过期之前完成,或者在上述情况下失败,该怎么办
共 (0) 个答案