Example usage for java.util.concurrent TimeoutException TimeoutException

List of usage examples for java.util.concurrent TimeoutException TimeoutException

Introduction

In this page you can find the example usage for java.util.concurrent TimeoutException TimeoutException.

Prototype

public TimeoutException(String message) 

Source Link

Document

Constructs a TimeoutException with the specified detail message.

Usage

From source file:org.cloudifysource.esc.installer.AgentlessInstaller.java

/*******
 * Checks if a TCP connection to a remote machine and port is possible.
 * //from w  ww  . ja va 2 s . co m
 * @param ip
 *            remote machine ip.
 * @param port
 *            remote machine port.
 * @param installerConfiguration
 *            .
 * @param timeout
 *            duration to wait for successful connection.
 * @param unit
 *            time unit to wait.
 * @throws InstallerException .
 * @throws TimeoutException .
 * @throws InterruptedException .
 */
public static void checkConnection(final String ip, final int port,
        final CloudTemplateInstallerConfiguration installerConfiguration, final long timeout,
        final TimeUnit unit) throws TimeoutException, InterruptedException, InstallerException {

    final long end = System.currentTimeMillis() + unit.toMillis(timeout);

    final InetAddress inetAddress = waitForRoute(installerConfiguration, ip,
            Math.min(end, System.currentTimeMillis()
                    + installerConfiguration.getConnectionTestRouteResolutionTimeoutMillis()));
    final InetSocketAddress socketAddress = new InetSocketAddress(inetAddress, port);

    logger.fine("Checking connection to: " + socketAddress);
    while (System.currentTimeMillis() + installerConfiguration.getConnectionTestIntervalMillis() < end) {

        // need to sleep since sock.connect may return immediately, and
        // server may take time to start
        Thread.sleep(installerConfiguration.getConnectionTestIntervalMillis());

        final Socket sock = new Socket();
        try {
            sock.connect(socketAddress, installerConfiguration.getConnectionTestConnectTimeoutMillis());
            return;
        } catch (final IOException e) {
            logger.log(Level.FINE, "Checking connection to: " + socketAddress, e);
            // retry
        } finally {
            if (sock != null) {
                try {
                    sock.close();
                } catch (final IOException e) {
                    logger.fine("Failed to close socket");
                }
            }
        }
    }

    //timeout was reached
    String ipAddress = inetAddress.getHostAddress(); //if resolving fails we don't reach this line
    throw new TimeoutException("Failed connecting to " + IPUtils.getSafeIpAddress(ipAddress) + ":" + port);

}

From source file:com.vmware.photon.controller.common.dcp.ServiceHostUtils.java

public static void waitForNodeGroupConvergence(ServiceHost localHost,
        Collection<Pair<String, Integer>> remoteHostIpAndPortPairs, String nodeGroupPath, int maxRetries,
        int retryInterval) throws Throwable {
    checkArgument(localHost != null, "localHost cannot be null");
    checkArgument(remoteHostIpAndPortPairs != null, "remoteHostIpAndPortPairs cannot be null");
    checkArgument(!Strings.isNullOrEmpty(nodeGroupPath), "nodeGroupPath cannot be null or empty");
    checkArgument(maxRetries > 0, "maxRetries must be > 0");

    if (remoteHostIpAndPortPairs.size() == 1) {
        // nothing to synchronize if we only have one host
        return;//ww  w. ja  va2s  .  co m
    }

    for (Pair<String, Integer> remoteHostIpAndPortPair : remoteHostIpAndPortPairs) {

        int checkRetries = maxRetries;
        int checksToConvergence = REQUIRED_STABLE_STATE_COUNT;
        while (checkRetries > 0 && checksToConvergence > 0) {
            // update retry count and sleep
            checkRetries--;
            Thread.sleep(retryInterval * checksToConvergence);

            // check the host response
            NodeGroupService.NodeGroupState response = getNodeGroupState(localHost,
                    remoteHostIpAndPortPair.getKey(), remoteHostIpAndPortPair.getValue(), nodeGroupPath);
            if (response.nodes.size() < remoteHostIpAndPortPairs.size()) {
                continue;
            }

            // check host status
            checksToConvergence--;
            for (NodeState nodeState : response.nodes.values()) {
                if (nodeState.status != NodeState.NodeStatus.AVAILABLE) {
                    checksToConvergence = REQUIRED_STABLE_STATE_COUNT;
                    break;
                    // Note that we are not breaking from the above while loop where checksToConvergence is done
                    // This is because the nodes might switch between AVAILABLE and SYNCHRONIZING as the other nodes join
                }
            }
        }

        if (checkRetries == 0) {
            throw new TimeoutException("nodes did not converge");
        }
    }
}

From source file:com.vmware.photon.controller.common.xenon.ServiceHostUtils.java

public static void waitForNodeGroupConvergence(ServiceHost localHost,
        Collection<Pair<String, Integer>> remoteHostIpAndPortPairs, String nodeGroupPath, int maxRetries,
        int retryInterval) throws Throwable {
    checkArgument(localHost != null, "localHost cannot be null");
    checkArgument(remoteHostIpAndPortPairs != null, "remoteHostIpAndPortPairs cannot be null");
    checkArgument(!Strings.isNullOrEmpty(nodeGroupPath), "nodeGroupPath cannot be null or empty");
    checkArgument(maxRetries > 0, "maxRetries must be > 0");

    for (Pair<String, Integer> remoteHostIpAndPortPair : remoteHostIpAndPortPairs) {

        int checkRetries = maxRetries;
        int checksToConvergence = REQUIRED_STABLE_STATE_COUNT;
        while (checkRetries > 0 && checksToConvergence > 0) {
            // update retry count and sleep
            checkRetries--;// w  w w  .j a va 2s  . c  om
            Thread.sleep(retryInterval * checksToConvergence);

            // check the host response
            NodeGroupService.NodeGroupState response = getNodeGroupState(localHost,
                    remoteHostIpAndPortPair.getKey(), remoteHostIpAndPortPair.getValue(), nodeGroupPath);
            if (response.nodes.size() < remoteHostIpAndPortPairs.size()) {
                continue;
            }

            // check host status
            checksToConvergence--;
            for (NodeState nodeState : response.nodes.values()) {
                if (nodeState.status != NodeState.NodeStatus.AVAILABLE) {
                    checksToConvergence = REQUIRED_STABLE_STATE_COUNT;
                    break;
                    // Note that we are not breaking from the above while loop where checksToConvergence is done
                    // This is because the nodes might switch between AVAILABLE and SYNCHRONIZING as the other nodes join
                }
            }
        }

        if (checkRetries == 0) {
            throw new TimeoutException("nodes did not converge");
        }
    }
}

From source file:org.apache.geode.internal.process.FileProcessController.java

private String status(final File workingDir, final String statusRequestFileName, final String statusFileName)
        throws IOException, InterruptedException, TimeoutException {
    // monitor for statusFile
    File statusFile = new File(workingDir, statusFileName);
    AtomicReference<String> statusRef = new AtomicReference<>();

    ControlRequestHandler statusHandler = () -> {
        // read the statusFile
        StringBuilder lines = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(statusFile))) {
            reader.lines().forEach(lines::append);
        } finally {
            statusRef.set(lines.toString());
        }//from w w  w.j  av  a2  s.  c o  m
    };

    ControlFileWatchdog statusFileWatchdog = new ControlFileWatchdog(workingDir, statusFileName, statusHandler,
            true);
    statusFileWatchdog.start();

    File statusRequestFile = new File(workingDir, statusRequestFileName);
    if (!statusRequestFile.exists()) {
        statusRequestFile.createNewFile();
    }

    // if timeout invoke stop and then throw TimeoutException
    long start = System.currentTimeMillis();
    while (statusFileWatchdog.isAlive()) {
        Thread.sleep(10);
        if (System.currentTimeMillis() >= start + statusTimeoutMillis) {
            statusFileWatchdog.stop();
            throw new TimeoutException("Timed out waiting for process to create " + statusFile);
        }
    }

    String lines = statusRef.get();
    if (isBlank(lines)) {
        throw new IllegalStateException("Status file '" + statusFile + "' is blank");
    }
    return lines;
}

From source file:com.reactivetechnologies.platform.analytics.WekaMessagingChannel.java

/**
 * Request a dump of classifier models from all cluster members
 * @param duration/*from  w  w  w  .  ja  v  a  2s.co m*/
 * @param unit
 * @return
 * @throws InterruptedException
 * @throws TimeoutException 
 */
public boolean tryMemberSnapshot(long duration, TimeUnit unit) throws InterruptedException, TimeoutException {
    boolean snapshotDone = false;
    boolean locked = hzService.acquireLock(TimeUnit.SECONDS, 10);
    try {
        if (locked) {
            snapshotDone = signalAndAwait(duration, unit);
            if (!snapshotDone)
                throw new TimeoutException("Operation timed out in [" + duration + " " + unit
                        + "] before getting response from all members");
        }
    } finally {
        hzService.releaseLock(true);
    }

    return snapshotDone;
}

From source file:com.ebay.pulsar.analytics.memcachedcache.MemcachedCacheTest.java

@Test
public void MemcachedCache() {
    // MemcachedCacheConfig test
    final MemcachedCacheConfig mc = new MemcachedCacheConfig();
    mc.setMaxObjectSize(mc.getMaxObjectSize());
    mc.setMaxOperationQueueSize(mc.getMaxOperationQueueSize());
    mc.setMemcachedPrefix(mc.getMemcachedPrefix());
    mc.setReadBufferSize(mc.getReadBufferSize());
    mc.setTimeout(mc.getMaxObjectSize());
    Assert.assertTrue(mc.getHosts() == null);
    //ArrayList<String> al2 = new ArrayList<String>();
    //al2.add("localhost:8080");
    mc.setHosts("localhost:8080");

    MemcachedCache INSTANCE = MemcachedCache.create(mc);

    Assert.assertTrue(INSTANCE != null);

    MemcachedClientIF client = Mockito.mock(MemcachedClientIF.class);
    try {/* ww  w  .  j  ava2 s .c  o m*/
        ReflectFieldUtil.setField(INSTANCE, "client", client);
    } catch (Exception e) {
        e.printStackTrace();
    }

    //regular test
    final NamedKey nk = new NamedKey("space", "key".getBytes());

    when(client.set(computeKeyHash(mc.getMemcachedPrefix(), nk), 1000, serializeValue(nk, "result".getBytes())))
            .thenAnswer(new Answer<Future<Boolean>>() {
                public Future<Boolean> answer(InvocationOnMock invocation) throws Throwable {
                    //Future<Boolean> future = Mockito.mock(FutureTask.class);
                    when(future1.get()).thenReturn(true);
                    return future1;
                }
            });

    try {
        INSTANCE.put(nk, "result".getBytes(), 1000);
    } catch (Exception e) {
        e.printStackTrace();
    }

    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nk))).thenAnswer(new Answer<Future<Object>>() {
        public Future<Object> answer(InvocationOnMock invocation) throws Throwable {
            //Future<Object> future = Mockito.mock(FutureTask.class);
            when(future2.get(mc.getTimeout(), TimeUnit.MILLISECONDS))
                    .thenReturn(serializeValue(nk, "result".getBytes()));
            return future2;
        }
    });

    String re = new String(INSTANCE.get(nk));
    Assert.assertTrue(re.equals("result"));

    /////client exception
    final NamedKey nkIllegalStateException = new NamedKey("space", "IllegalStateException".getBytes());

    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nkIllegalStateException)))
            .thenThrow(new IllegalStateException("nkIllegalStateException"));

    Assert.assertTrue(INSTANCE.get(nkIllegalStateException) == null);

    //future exception
    final NamedKey nkTimeoutException = new NamedKey("space", "TimeoutException".getBytes());
    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nkTimeoutException)))
            .thenAnswer(new Answer<Future<Object>>() {
                public Future<Object> answer(InvocationOnMock invocation) throws Throwable {
                    //Future<Object> future = Mockito.mock(FutureTask.class);
                    when(future3.get(mc.getTimeout(), TimeUnit.MILLISECONDS))
                            .thenThrow(new TimeoutException("TimeoutException"));
                    return future3;
                }
            });
    Assert.assertTrue(INSTANCE.get(nkTimeoutException) == null);

    final NamedKey nkInterruptedException = new NamedKey("space", "InterruptedException".getBytes());
    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nkInterruptedException)))
            .thenAnswer(new Answer<Future<Object>>() {
                public Future<Object> answer(InvocationOnMock invocation) throws Throwable {
                    //Future<Object> future = Mockito.mock(FutureTask.class);
                    when(future4.get(mc.getTimeout(), TimeUnit.MILLISECONDS))
                            .thenThrow(new InterruptedException("InterruptedException"));
                    return future4;
                }
            });
    try {
        Assert.assertTrue(INSTANCE.get(nkInterruptedException) == null);
    } catch (Exception e) {

    }

    final NamedKey nkExecutionException = new NamedKey("space", "ExecutionException".getBytes());
    when(client.asyncGet(computeKeyHash(mc.getMemcachedPrefix(), nkExecutionException)))
            .thenAnswer(new Answer<Future<Object>>() {
                public Future<Object> answer(InvocationOnMock invocation) throws Throwable {
                    //Future<Object> future = Mockito.mock(FutureTask.class);
                    when(future5.get(mc.getTimeout(), TimeUnit.MILLISECONDS)).thenThrow(
                            new ExecutionException("ExecutionException", new Exception("ExecutionException")));
                    return future5;
                }
            });
    Assert.assertTrue(INSTANCE.get(nkExecutionException) == null);

    ////////test bulk

    //get bulk fail
    final NamedKey nkIllegalStateExceptionBulk = new NamedKey("space", "IllegalStateException".getBytes());
    ArrayList<NamedKey> a1 = new ArrayList<NamedKey>();
    a1.add(nkIllegalStateExceptionBulk);
    Map<String, NamedKey> keyLookup = Maps.uniqueIndex(a1, new Function<NamedKey, String>() {
        @Override
        public String apply(NamedKey input) {
            return computeKeyHash(mc.getMemcachedPrefix(), input);
        }
    });

    when(client.asyncGetBulk(keyLookup.keySet()))
            .thenThrow(new IllegalStateException("nkIllegalStateException"));

    Assert.assertTrue(INSTANCE.getBulk(a1).size() == 0);

    //test future
    final NamedKey some = new NamedKey("space", "resultsome".getBytes());
    ArrayList<NamedKey> a2 = new ArrayList<NamedKey>();
    a2.add(some);
    Map<String, NamedKey> keyLookup2 = Maps.uniqueIndex(a2, new Function<NamedKey, String>() {
        @Override
        public String apply(NamedKey input) {
            return computeKeyHash(mc.getMemcachedPrefix(), input);
        }
    });

    when(client.asyncGetBulk(keyLookup2.keySet())).thenAnswer(new Answer<BulkFuture<Map<String, Object>>>() {
        public BulkFuture<Map<String, Object>> answer(InvocationOnMock invocation) throws Throwable {
            //BulkFuture<Map<String, Object>> future = Mockito.mock(BulkFuture.class);
            Map<String, Object> mp = new HashMap<String, Object>();
            mp.put(computeKeyHash(mc.getMemcachedPrefix(), some), serializeValue(some, "result".getBytes()));
            when(future8.getSome(mc.getTimeout(), TimeUnit.MILLISECONDS)).thenReturn(mp);
            return future8;
        }
    });

    String somere = new String(INSTANCE.getBulk(a2).get(some));
    Assert.assertTrue(somere.equals("result"));

    //test bulk exception
    final NamedKey someInterruptedException = new NamedKey("space", "someInterruptedException".getBytes());
    ArrayList<NamedKey> a3 = new ArrayList<NamedKey>();
    a3.add(someInterruptedException);
    Map<String, NamedKey> keyLookup3 = Maps.uniqueIndex(a3, new Function<NamedKey, String>() {
        @Override
        public String apply(NamedKey input) {
            return computeKeyHash(mc.getMemcachedPrefix(), input);
        }
    });

    when(client.asyncGetBulk(keyLookup3.keySet())).thenAnswer(new Answer<BulkFuture<Map<String, Object>>>() {
        public BulkFuture<Map<String, Object>> answer(InvocationOnMock invocation) throws Throwable {
            //BulkFuture<Map<String, Object>> future = Mockito.mock(BulkFuture.class);
            when(future6.getSome(mc.getTimeout(), TimeUnit.MILLISECONDS))
                    .thenThrow(new InterruptedException("someInterruptedException"));
            return future6;
        }
    });
    try {
        INSTANCE.getBulk(a3).get(someInterruptedException);
    } catch (Exception e) {
        System.out.println("Catch InterruptedException success!");
    }

    final NamedKey someExecutionException = new NamedKey("space", "someExecutionException".getBytes());
    ArrayList<NamedKey> a4 = new ArrayList<NamedKey>();
    a4.add(someExecutionException);
    Map<String, NamedKey> keyLookup4 = Maps.uniqueIndex(a4, new Function<NamedKey, String>() {
        @Override
        public String apply(NamedKey input) {
            return computeKeyHash(mc.getMemcachedPrefix(), input);
        }
    });

    when(client.asyncGetBulk(keyLookup4.keySet())).thenAnswer(new Answer<BulkFuture<Map<String, Object>>>() {
        public BulkFuture<Map<String, Object>> answer(InvocationOnMock invocation) throws Throwable {
            //BulkFuture<Map<String, Object>> future = Mockito.mock(BulkFuture.class);
            when(future7.getSome(mc.getTimeout(), TimeUnit.MILLISECONDS)).thenThrow(
                    new ExecutionException("someExecutionException", new Exception("someExecutionException")));
            return future7;
        }
    });

    Assert.assertTrue(INSTANCE.getBulk(a4).get(someExecutionException) == null);

    CacheStats st = INSTANCE.getStats();
    Assert.assertTrue(st.getNumErrors() == 4);
    Assert.assertTrue(st.getNumHits() == 2);
    Assert.assertTrue(st.getNumMisses() == 0);
}

From source file:io.github.retz.web.ClientHelper.java

public static Optional<Job> getWholeFileWithTerminator(Client c, int id, String filename, boolean poll,
        OutputStream out, long offset, Callable<Boolean> terminator)
        throws IOException, JobNotFoundException, TimeoutException {
    Optional<Job> current;/*w  ww .  j a va2  s .co m*/

    {
        Response res = c.getJob(id);
        if (!(res instanceof GetJobResponse)) {
            LOG.error(res.status());
            throw new IOException(res.status());
        }
        GetJobResponse getJobResponse = (GetJobResponse) res;
        if (!getJobResponse.job().isPresent()) {
            throw new JobNotFoundException(id);
        }
    }

    int interval = INITAL_INTERVAL_MSEC;
    Job.JobState currentState = Job.JobState.QUEUED;

    long bytesRead = readFileUntilEmpty(c, id, filename, offset, out);
    offset = offset + bytesRead;

    do {
        Response res = c.getJob(id);
        if (!(res instanceof GetJobResponse)) {
            LOG.error(res.status());
            throw new IOException(res.status());
        }
        GetJobResponse getJobResponse = (GetJobResponse) res;
        current = getJobResponse.job();

        bytesRead = readFileUntilEmpty(c, id, filename, offset, out);
        offset = offset + bytesRead;

        if (current.isPresent()) {
            currentState = current.get().state();
            if ((currentState == Job.JobState.FINISHED || currentState == Job.JobState.KILLED)
                    && bytesRead == 0) {
                break;
            }
        }

        if (poll) {
            maybeSleep(interval);

            if (bytesRead == 0) {
                interval = Math.min(interval * 2, MAX_INTERVAL_MSEC);
            } else {
                interval = INITAL_INTERVAL_MSEC;
            }

            try {
                if (terminator != null && terminator.call()) {
                    throw new TimeoutException("Timeout at getWholeFile");
                }
            } catch (TimeoutException e) {
                throw e;
            } catch (Exception e) {
                LOG.error(e.toString(), e);
                return current; // I don't know how to handle it
            }
        } else {
            break;
        }
    } while (currentState != Job.JobState.FINISHED && currentState != Job.JobState.KILLED);

    if (!ClientHelper.fileExists(c, id, filename)) {
        // TODO: remove a file if it's already created
        throw new FileNotFoundException(filename);
    }

    return current;
}

From source file:org.apache.geode.internal.statistics.DiskSpaceLimitIntegrationTest.java

private void sampleUntilFileExists(final File file) throws InterruptedException, TimeoutException {
    long minutes = 1;
    long timeout = System.nanoTime() + MINUTES.toNanos(minutes);
    int count = 0;
    do {/* ww  w.j  av  a  2 s .  c  o  m*/
        sample(advanceNanosTimeStamp());
        count++;
        Thread.sleep(10);
    } while (!everExisted(file) && System.nanoTime() < timeout);
    if (!everExisted(file)) {
        throw new TimeoutException("File " + file + " does not exist after " + count + " samples within "
                + minutes + " " + MINUTES);
    }
    System.out.println("Sampled " + count + " times to create " + file);
}

From source file:com.ibm.jaggr.core.impl.modulebuilder.less.LessModuleBuilder.java

protected String processLess(String filename, String css) throws IOException {
    final String sourceMethod = "processLess"; //$NON-NLS-1$
    final boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(sourceClass, sourceMethod, new Object[] { filename, css });
    }/*from  w ww  .  ja  v a 2 s  . c o  m*/
    Context cx = Context.enter();
    Scriptable threadScope = null;
    try {
        threadScope = getThreadScopes().poll(SCOPE_POOL_TIMEOUT_SECONDS, TimeUnit.SECONDS);
        if (threadScope == null) {
            throw new TimeoutException("Timeout waiting for thread scope"); //$NON-NLS-1$
        }
        Scriptable scope = cx.newObject(threadScope);
        scope.setParentScope(threadScope);
        Scriptable options = cx.newObject(threadScope);
        options.put("filename", options, filename); //$NON-NLS-1$
        Function compiler = (Function) threadScope.get(LESS_COMPILER_VAR, threadScope);
        css = compiler.call(cx, scope, null, new Object[] { css, options }).toString();

    } catch (JavaScriptException e) {
        // Add module info
        String message = "Error parsing " + filename + "\r\n" + e.getMessage(); //$NON-NLS-1$ //$NON-NLS-2$
        throw new IOException(message, e);
    } catch (InterruptedException e) {
        throw new IOException(e);
    } catch (TimeoutException e) {
        throw new RuntimeException(e);
    } finally {
        if (threadScope != null) {
            getThreadScopes().add(threadScope);
        }
        Context.exit();
    }
    if (isTraceLogging) {
        log.exiting(sourceMethod, sourceMethod, css);
    }
    return css;
}

From source file:org.zlogic.voidreader.feed.Feed.java

/**
 * Handles downloaded feed entries/*from ww  w.  ja  v  a2  s  .  co m*/
 *
 * @param entries the downloaded entries
 * @param handler the feed item handler
 * @param cacheExpiryDate the date after which feed items expire and can be
 * removed
 * @param maxRunSeconds the maximum time application can run before being
 * forcefully terminated
 * @throws IOException if FeedItem constructor fails (e.g. unable to
 * generate HTML based on the template)
 * @throws TimeoutException if the task took too long to complete
 */
private void handleEntries(List<Object> entries, FeedItemHandler handler, Date cacheExpiryDate,
        int maxRunSeconds) throws IOException, TimeoutException {
    if (items == null)
        items = new TreeSet<>();
    Set<FeedItem> newItems = new TreeSet<>();
    for (Object obj : entries)
        if (obj instanceof SyndEntry)
            newItems.add(new FeedItem(this, (SyndEntry) obj));

    //Find outdated items
    for (FeedItem oldItem : new TreeSet<>(items))
        if (!newItems.contains(oldItem) && oldItem.getLastSeen() != null
                && oldItem.getLastSeen().before(cacheExpiryDate)) {
            items.remove(oldItem);
        } else if (newItems.contains(oldItem)) {
            for (FeedItem newItem : newItems)
                if (newItem.equals(oldItem))
                    newItem.setState(oldItem.getState());//Transfer state to new item
            if (oldItem.getState() != FeedItem.State.SENT_PDF)
                items.remove(oldItem);//Replace with new item to resend pdf
            else
                oldItem.updateLastSeen();
        }

    // Ignore already existing items
    newItems.removeAll(items);

    //Add new items
    items.addAll(newItems);
    ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());//TODO: make this configurable
    for (FeedItem item : newItems) {
        executor.submit(new Runnable() {
            private FeedItemHandler handler;
            private Feed feed;
            private FeedItem item;

            public Runnable setParameters(FeedItemHandler handler, Feed feed, FeedItem item) {
                this.handler = handler;
                this.feed = feed;
                this.item = item;
                return this;
            }

            @Override
            public void run() {
                try {
                    handler.handle(feed, item);
                } catch (RuntimeException ex) {
                    log.log(Level.SEVERE, MessageFormat.format(messages.getString("ERROR_HANDLING_FEED_ITEM"),
                            new Object[] { item }), ex);
                    synchronized (items) {
                        items.remove(item);
                    }
                }
            }
        }.setParameters(handler, this, item));
    }
    executor.shutdown();
    try {
        if (!executor.awaitTermination(maxRunSeconds > 0 ? maxRunSeconds : Long.MAX_VALUE, TimeUnit.SECONDS)) {
            throw new TimeoutException(messages.getString("TIMED_OUT_WAITING_FOR_EXECUTOR"));
        }
    } catch (InterruptedException ex) {
        throw new RuntimeException(ex);
    }
}