gpt4 book ai didi

java - Java多线程-避免重复请求处理

转载 作者:行者123 更新时间:2023-12-03 12:53:16 25 4
gpt4 key购买 nike

我有以下多线程环境方案-请求正在传入一个方法,并且我想避免重复处理并发请求。由于可能有多个类似的请求正在等待处于阻塞状态的处理。我使用哈希表来跟踪已处理的请求,但是它将导致内存泄漏,因此应如何跟踪已处理的请求并避免可能处于阻塞状态的相同请求被处理。

如何检查是否有任何等待/阻塞的传入请求不是当前线程中正在处理的请求。

最佳答案

好吧,我想我有点明白你想要什么。

您可以将ConcurrentSkipListSet用作队列。像这样实现您排队的元素:

 class Element implements Comparable<Element> {
//To FIFOnize
private static final AtomicLong SEQ = new AtomicLong();
private final long id = SEQ.incrementAndGet();

//Can only be executed once.
private final Semaphore execPermission = new Semaphore(1);


public int compareTo(Element e){
// If element e1 exists on the queue such that
// e.compareTo(e1) == 0, that element will not
// be placed on the queue.
if(this.equals(e)){
return 0;
}else{
//This will enforce FIFO.
this.id > e.id ? 1 : ( this.id < e.id ? -1 : 0);
}
}
//implement both equals and hashCode

public boolean tryAcquire(){
return execPermission.tryAcquire();
}
}

现在您的线程应该,
 while(!Thread.currentThread().isInterrupted()){
//Iterates from head, therefore simulates FIFO
for(Element e : queue){
if(e.tryAcquire()){
execute(e); //synchronous
queue.remove(e);
}
}
}

您也可以使用此解决方案的阻塞变体(具有有限的SortedSet,并在没有元素等的情况下让工作线程阻塞)。

关于java - Java多线程-避免重复请求处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2559180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com