Image

Imagemihhon wrote in Imageru_java

multithreading, ConcurrentModificationException

насколько распространена практика писать такой "threadsafe" код?

    /**
     * Tries to remove from the work queue all {@link Future}
     * tasks that have been cancelled. This method can be useful as a
     * storage reclamation operation, that has no other impact on
     * functionality. Cancelled tasks are never executed, but may
     * accumulate in work queues until worker threads can actively
     * remove them. Invoking this method instead tries to remove them now.
     * However, this method may fail to remove tasks in
     * the presence of interference by other threads.
     */
    public void purge() {
        // Fail if we encounter interference during traversal
        try {
            Iterator it = getQueue().iterator();
            while (it.hasNext()) {
                Runnable r = (Runnable)it.next();
                if (r instanceof Future) {
                    Future c = (Future)r;
                    if (c.isCancelled())
                        it.remove();
                }
            }
        }
        catch (ConcurrentModificationException ex) {
            return;
        }
    }


(кусок ThreadPoolExecutor, backport util.concurrent на jdk1.4, @author Doug Lea)