Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is how I would handle and avoid duplicates</p> <pre><code>import java.util.Collections; import java.util.Set; import java.util.concurrent.*; public class TestExecution implements Callable&lt;Void&gt; { private static final ThreadPoolExecutor TPE = new ThreadPoolExecutor(2, 5, 1, TimeUnit.MINUTES, new LinkedBlockingQueue&lt;Runnable&gt;()); private static final Set&lt;TestExecution&gt; TE_SET = Collections.newSetFromMap(new ConcurrentHashMap&lt;TestExecution, Boolean&gt;()); private final String key1; private final String key2; public static void main(String... args) throws InterruptedException { new TestExecution("A", "A").execute(); new TestExecution("A", "A").execute(); new TestExecution("B", "B").execute(); Thread.sleep(8000); new TestExecution("A", "A").execute(); new TestExecution("B", "B").execute(); new TestExecution("B", "B").execute(); TPE.shutdown(); } public TestExecution(String key1, String key2) { this.key1 = key1; this.key2 = key2; } void execute() { if (TE_SET.add(this)) { System.out.println("Handling " + this); TPE.submit(this); } else { System.out.println("... ignoring duplicate " + this); } } public boolean equals(Object obj) { return obj instanceof TestExecution &amp;&amp; key1.equals(((TestExecution) obj).key1) &amp;&amp; key2.equals(((TestExecution) obj).key2); } public int hashCode() { return key1.hashCode() * 31 + key2.hashCode(); } @Override public Void call() throws InterruptedException { if (!TE_SET.remove(this)) { System.out.println("... dropping duplicate " + this); return null; } System.out.println("Start processing " + this); Thread.sleep(4000); System.out.println("Finish processing " + this); return null; } public String toString() { return key1 + ':' + key2; } } </code></pre> <p>prints</p> <pre><code>Handling A:A ... ignoring duplicate A:A Handling B:B Start processing A:A Start processing B:B Finish processing A:A Finish processing B:B Handling A:A Handling B:B Start processing A:A Start processing B:B ... ignoring duplicate B:B Finish processing B:B Finish processing A:A </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload