I have a serial connection which shall only be used by a single thread. But before I submit a new Task to the executors I want check if that certain Task is already in the queu(e.g for polling values).
executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
TaskRunnable runn = new TaskRunnable(
Integer.toString(i), "42");
if (!executor.getQueue().contains(runn)) {
executor.submit(runn);
}
}
}
}
}).start();
public void write(String addr, String value) {
// write
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
class TaskRunnable implements Runnable {
String addr, value;
public TaskRunnable(String addr, String value) {
this.addr = addr;
this.value = value;
}
@Override
public void run() {
write(addr, value);
System.out.println("Executed: " + addr + " - "
+ executor.getQueue().size());
}
@Override
public boolean equals(Object obj) {
TaskRunnable other = (TaskRunnable) obj;
return this.addr.equals(other.addr);
}
@Override
public int hashCode() {
int hash = 7;
hash = 17 * hash + (this.addr != null ? this.addr.hashCode() : 0);
return hash;
}
}
If I check executor.getQueue()
the type is BlockingQueue<Runnable>
but if I do executor.getQueue().contains(task)
the equals method of TaskRunnable
is called with an object of type FutureTask
and I get this exception
java.util.concurrent.FutureTask cannot be cast to ExecutorTest$TaskRunnable
Any Idea how I can check If a certain TaskRunnable
is already in the queue?