Example usage for java.util.concurrent ExecutorService submit

List of usage examples for java.util.concurrent ExecutorService submit

Introduction

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

Prototype

Future<?> submit(Runnable task);

Source Link

Document

Submits a Runnable task for execution and returns a Future representing that task.

Usage

From source file:com.clustercontrol.agent.SendQueue.java

/**
 * ????<BR>/*from w w w  .  j a va  2s  . co  m*/
 * 
 * ?????????<BR>
 * ??????
 * @param msg
 */
public boolean put(Object info) {
    m_log.debug("put() start : " + info.getClass().getCanonicalName());

    while (!ReceiveTopic.isHistoryClear()) {
        m_log.debug("put() while (!ReceiveTopic.isHistoryClear()) is true");

        boolean sendQueueStatus = false;
        ExecutorService es = null;
        Future<Boolean> task = null;
        try {
            String id = "";
            // Executor??
            SenderThreadFactory threadFactory = new SenderThreadFactory(id);
            es = Executors.newSingleThreadExecutor(threadFactory);

            // Queue??
            // ?Queue??????????????????
            // Future.get()????????
            m_log.debug("put() submit");
            task = es.submit(new Sender(info));
            sendQueueStatus = task.get(SEND_TIMEOUT, TimeUnit.MILLISECONDS);

        } catch (Exception e) {
            // Queue?????????????Future.get()???????
            // ????

            // ?
            m_log.warn("put() : Failed to connect to MGR " + e.getMessage(), e);

        } finally {
            // 
            if (task != null) {
                task.cancel(true);
            }

            if (es != null) {
                es.shutdown();
            }
            m_log.debug("put() end    : " + info.getClass().getCanonicalName());
        }

        // ??????????sleep????
        // Queue????????
        if (sendQueueStatus) {
            m_log.debug("put() return true : " + info.getClass().getCanonicalName());
            return true;
        } else {
            // sleep???QueueConnection?QueueSession ??
            try {
                m_log.debug("put() reput interval sleep: " + m_sendQueueReconnectionInterval + " sec");
                Thread.sleep(m_sendQueueReconnectionInterval);
            } catch (InterruptedException e1) {
                m_log.error("put() reput interval sleep: ", e1);
            }
        }
    } // End While Loop
    return false;
}

From source file:com.opengamma.engine.cache.BerkeleyDBValueIdentifierMapTest.java

@Test(timeOut = 30000)
public void interruptThread() throws Throwable {
    final ExecutorService threads = Executors.newSingleThreadExecutor();
    try {/*w w w  . j  a v a  2  s  .  c  o  m*/
        final Thread main = Thread.currentThread();
        final Runnable interrupter = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    main.interrupt();
                } catch (InterruptedException e) {
                    throw new OpenGammaRuntimeException("Interrupted", e);
                }
            }
        };
        threads.submit(interrupter);
        int count = 0;
        do {
            try {
                getPerformanceTest();
            } catch (OpenGammaRuntimeException e) {
                assertEquals("Interrupted", e.getMessage());
                count++;
                if (count <= 5) {
                    threads.submit(interrupter);
                } else {
                    break;
                }
            }
        } while (true);
    } finally {
        threads.shutdown();
        Thread.interrupted();
        threads.awaitTermination(5, TimeUnit.SECONDS);
    }
}

From source file:de.tudarmstadt.lt.seg.app.Segmenter.java

private void run_parallel() throws Exception {

    InputStream in = System.in;
    if (!"-".equals(_filename_in))
        in = new FileInputStream(_filename_in);
    Stream<String> liter = new BufferedReader(new InputStreamReader(in, Charset.defaultCharset())).lines();

    ThreadLocal<ISentenceSplitter> sentenceSplitter = ThreadLocal.withInitial(() -> {
        try {/*  w ww .ja v  a2  s. c o m*/
            return newSentenceSplitter();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    });
    ThreadLocal<ITokenizer> tokenizer = ThreadLocal.withInitial(() -> {
        try {
            return newTokenizer();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    });

    final PrintWriter[] w = new PrintWriter[_parallelism];
    // init writers
    for (int i = 0; i < _parallelism; i++) {
        OutputStream out = System.out;
        if (!"-".equals(_filename_out)) {
            out = new FileOutputStream(String.format("%s_%d", _filename_out, i));
        }
        w[i] = new PrintWriter(new OutputStreamWriter(out, Charset.defaultCharset()));
    }

    BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(_parallelism * 2, true);
    ExecutorService es = new ThreadPoolExecutor(_parallelism, _parallelism, 0L, TimeUnit.MILLISECONDS, queue);

    AtomicLong lc = new AtomicLong(0);
    liter.forEach((line) -> {
        // don't try to submit new threads, wait until the thread queue has some capacity again
        while (queue.remainingCapacity() == 0)
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                /**/}
        es.submit(() -> {
            final long docid = lc.incrementAndGet();
            if (docid % 1000 == 0)
                System.err.format("Processing line %d ('%s')%n", docid, _filename_in);
            final int w_i = (int) (docid % _parallelism);
            split_and_tokenize(new StringReader(line.trim()), String.format("%s:%d", _filename_in, docid),
                    sentenceSplitter.get(), tokenizer.get(), _level_filter, _level_normalize, _merge_types,
                    _merge_tokens, _separator_sentence, _separator_token, _separator_desc, w[w_i]);

        });
    });
    es.shutdown();
    es.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS);

    // TODO: the stream parallelism version does not work because it submits too many threads at once
    //      AtomicLong lc = new AtomicLong(0);
    //      ForkJoinPool forkJoinPool = new ForkJoinPool(_parallelism);
    //      forkJoinPool.submit(() -> 
    //         liter.parallel().forEach((line) -> {
    //            final long docid = lc.incrementAndGet();
    //            if(docid % 1000 == 0)
    //               System.err.format("Processing line %d ('%s')%n", docid, _filename_in);
    //   
    //            String l = line.replace("\\t", "\t").replace("\\n", "\n");
    //            split_and_tokenize(
    //                  new StringReader(l),
    //                  String.format("%s:%d", _filename_in, docid),
    //                  sentenceSplitter.get(), 
    //                  tokenizer.get(), 
    //                  _level_filter,
    //                  _level_normalize,
    //                  _merge_types,
    //                  _merge_tokens,
    //                  _separator_sentence,
    //                  _separator_token,
    //                  _separator_desc,
    //                  w);
    //      })).get();

}

From source file:com.shonshampain.streamrecorder.util.StreamProxy.java

@Override
public void run() {
    Socket client = null;//from   ww  w . ja  v  a  2s  .c  o  m
    HttpRequest request;

    Logger.d(DBG, TAG, "running");
    while (isRunning) {
        try {
            Logger.d(DBG, TAG, "Waiting on a connection");
            ExecutorService executor = Executors.newFixedThreadPool(1);
            Callable<Socket> task = new Callable<Socket>() {
                @Override
                public Socket call() throws Exception {
                    return socket.accept();
                }
            };
            Future<Socket> future = executor.submit(task);
            try {
                client = future.get(STREAM_STALLED_TIMEOUT, TimeUnit.MILLISECONDS);
            } catch (TimeoutException to) {
                startOver(null, null, FailType.SocketAccept, null);
                continue;
            } catch (InterruptedException ie) {
                Logger.e(TAG, "The read operation was interrupted");
            } catch (ExecutionException ee) {
                startOver(null, null, FailType.SocketAccept, null);
                continue;
            }
            if (client == null) {
                continue;
            }
            Logger.d(DBG, TAG, "client connected");
            request = readRequest(client);
            Logger.d(DBG, TAG, "calling process request...");
            if (request != null) {
                processRequest(request, client);
            }
            Logger.d(DBG, TAG, "...and we're back");
        } catch (SocketTimeoutException e) {
            Logger.d(DBG, TAG, "Socket timed out");
        } catch (IOException e) {
            Log.e(TAG, "Error connecting to client", e);
        }
    }
    Logger.d(DBG, TAG, "Proxy interrupted. Shutting down.");
}

From source file:com.amazonaws.mobileconnectors.s3.transfermanager.internal.UploadMonitor.java

/**
 * Constructs a new upload watcher, which immediately submits itself to the
 * thread pool.//from  ww w  . java2 s.c  o m
 *
 * @param manager The {@link TransferManager} that owns this upload.
 * @param transfer The transfer being processed.
 * @param threadPool The {@link ExecutorService} to which we should submit
 *            new tasks.
 * @param multipartUploadCallable The callable responsible for processing
 *            the upload asynchronously
 * @param putObjectRequest The original putObject request
 * @param progressListenerChain A chain of listeners that wish to be
 *            notified of upload progress
 */
public UploadMonitor(TransferManager manager, UploadImpl transfer, ExecutorService threadPool,
        UploadCallable multipartUploadCallable, PutObjectRequest putObjectRequest,
        ProgressListenerChain progressListenerChain) {

    this.s3 = manager.getAmazonS3Client();
    this.configuration = manager.getConfiguration();

    this.multipartUploadCallable = multipartUploadCallable;
    this.threadPool = threadPool;
    this.putObjectRequest = putObjectRequest;
    this.progressListenerChainCallbackExecutor = ProgressListenerCallbackExecutor
            .wrapListener(progressListenerChain);
    this.transfer = transfer;

    setNextFuture(threadPool.submit(this));
}

From source file:org.ngrinder.perftest.service.AgentManager.java

/**
 * Assign the agents on the given console.
 *
 * @param user              user/* w  w  w.  ja va2  s  .  c  o  m*/
 * @param singleConsole     {@link SingleConsole} to which agents will be assigned
 * @param grinderProperties {@link GrinderProperties} to be distributed.
 * @param agentCount        the count of agents.
 */
public synchronized void runAgent(User user, final SingleConsole singleConsole,
        final GrinderProperties grinderProperties, final Integer agentCount) {
    final Set<AgentIdentity> allFreeAgents = getAllFreeApprovedAgentsForUser(user);
    final Set<AgentIdentity> necessaryAgents = selectAgent(user, allFreeAgents, agentCount);
    LOGGER.info("{} agents are starting for user {}", agentCount, user.getUserId());
    for (AgentIdentity each : necessaryAgents) {
        LOGGER.info("- Agent {}", each.getName());
    }
    ExecutorService execService = null;
    try {
        // Make the agents connect to console.
        grinderProperties.setInt(GrinderProperties.CONSOLE_PORT, singleConsole.getConsolePort());
        execService = ExecutorFactory.createThreadPool("agentStarter", NUMBER_OF_THREAD);
        for (final AgentIdentity eachAgentIdentity : necessaryAgents) {
            execService.submit(new Runnable() {
                @Override
                public void run() {
                    agentControllerServerDaemon.startAgent(grinderProperties, eachAgentIdentity);
                }
            });
        }
    } finally {
        if (execService != null) {
            execService.shutdown();
        }
    }
}

From source file:io.undertow.server.handlers.file.FileHandlerStressTestCase.java

@Test
public void simpleFileStressTest()
        throws IOException, ExecutionException, InterruptedException, URISyntaxException {
    ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
    try {//from   w  ww .ja va 2  s  . c o  m
        Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
        final ResourceHandler handler = new ResourceHandler(new PathResourceManager(rootPath, 10485760));

        final CacheHandler cacheHandler = new CacheHandler(new DirectBufferCache(1024, 10, 10480), handler);
        final PathHandler path = new PathHandler();
        path.addPrefixPath("/path", cacheHandler);
        final CanonicalPathHandler root = new CanonicalPathHandler();
        root.setNext(path);
        DefaultServer.setRootHandler(root);
        final List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < NUM_THREADS; ++i) {
            futures.add(executor.submit(new Runnable() {
                @Override
                public void run() {
                    TestHttpClient client = new TestHttpClient();
                    try {
                        for (int i = 0; i < NUM_REQUESTS; ++i) {
                            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/page.html");
                            HttpResponse result = client.execute(get);
                            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                            final String response = HttpClientUtils.readResponse(result);
                            Assert.assertTrue(response, response.contains("A web page"));
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        client.getConnectionManager().shutdown();
                    }
                }
            }));
        }
        for (Future<?> future : futures) {
            future.get();
        }

    } finally {
        executor.shutdown();
    }
}

From source file:info.magnolia.imaging.caching.CachingImageStreamerRepositoryTest.java

@Test
public void testRequestForSimilarUncachedImageOnlyGeneratesItOnce() throws Exception {
    final HierarchyManager srcHM = MgnlContext.getHierarchyManager("website");
    final String srcPath = "/foo/bar";
    ContentUtil.createPath(srcHM, srcPath);

    // ParameterProvider for tests - return a new instance of the same node everytime
    // if we'd return the same src instance everytime, the purpose of this test would be null
    final ParameterProviderFactory<Object, Content> ppf = new TestParameterProviderFactory(srcHM, srcPath);

    final OutputFormat png = new OutputFormat();
    png.setFormatName("png");

    final BufferedImage dummyImg = ImageIO.read(getClass().getResourceAsStream("/funnel.gif"));
    assertNotNull("Couldn't load dummy test image", dummyImg);

    final ImageGenerator<ParameterProvider<Content>> generator = mock(ImageGenerator.class);
    when(generator.getParameterProviderFactory()).thenReturn(ppf);
    when(generator.getName()).thenReturn("test");
    when(generator.getOutputFormat(isA(ParameterProvider.class))).thenReturn(png);

    // aaaaand finally, here's the real reason for this test !
    when(generator.generate(isA(ParameterProvider.class))).thenReturn(dummyImg);

    // yeah, we're using a "wrong" workspace for the image cache, to avoid having to setup a custom one in this test
    final HierarchyManager hm = MgnlContext.getHierarchyManager("config");
    final ImageStreamer streamer = new CachingImageStreamer(hm, ppf.getCachingStrategy(),
            new DefaultImageStreamer());

    // Generator instances will always be the same (including paramProvFac)
    // since they are instantiated with the module config and c2b.
    // ParamProv is a new instance every time.
    // streamer can (must) be the same - once single HM, one cache.

    // thread pool of 10, launching 8 requests, can we hit some concurrency please ?
    final ExecutorService executor = Executors.newFixedThreadPool(10);
    final ByteArrayOutputStream[] outs = new ByteArrayOutputStream[8];
    final Future[] futures = new Future[8];
    for (int i = 0; i < outs.length; i++) {
        outs[i] = new ByteArrayOutputStream();
        futures[i] = executor.submit(new TestJob(generator, streamer, outs[i]));
    }/*from  www . ja  va  2 s.  c o m*/
    executor.shutdown();
    executor.awaitTermination(30, TimeUnit.SECONDS);

    for (Future<?> future : futures) {
        assertTrue(future.isDone());
        assertFalse(future.isCancelled());
        // ignore the results of TestJob - all we care about is if an exception was thrown
        // and if there was any, it is kept in Future until we call Future.get()
        future.get();
    }

    final NodeData cachedNodeData = hm.getNodeData("/test/website/foo/bar/generated-image");
    // update node meta data
    Content cachedNode = hm.getContent("/test/website/foo/bar");
    cachedNode.getMetaData().setModificationDate();
    cachedNode.save();
    final InputStream res = cachedNodeData.getStream();
    final ByteArrayOutputStream cachedOut = new ByteArrayOutputStream();
    IOUtils.copy(res, cachedOut);

    // assert all outs are the same
    for (int i = 1; i < outs.length; i++) {
        // TODO assert they're all equals byte to byte to the source? or in size? can't as-is since we convert...
        final byte[] a = outs[i - 1].toByteArray();
        final byte[] b = outs[i].toByteArray();
        assertTrue(a.length > 0);
        assertEquals("Different sizes (" + Math.abs(a.length - b.length) + " bytes diff.) with i=" + i,
                a.length, b.length);
        assertTrue("not equals for outs/" + i, Arrays.equals(a, b));
        outs[i - 1] = null; // cleanup all those byte[], or we'll soon run out of memory
    }
    assertTrue("failed comparing last thread's result with what we got from hierarchyManager",
            Arrays.equals(outs[outs.length - 1].toByteArray(), cachedOut.toByteArray()));
    outs[outs.length - 1] = null;

    // now start again another bunch of requests... they should ALL get their results from the cache
    final ExecutorService executor2 = Executors.newFixedThreadPool(10);
    final ByteArrayOutputStream[] outs2 = new ByteArrayOutputStream[8];
    final Future[] futures2 = new Future[8];
    for (int i = 0; i < outs2.length; i++) {
        outs2[i] = new ByteArrayOutputStream();
        futures2[i] = executor2.submit(new TestJob(generator, streamer, outs2[i]));
    }
    executor2.shutdown();
    executor2.awaitTermination(30, TimeUnit.SECONDS);

    for (Future<?> future : futures2) {
        assertTrue(future.isDone());
        assertFalse(future.isCancelled());
        // ignore the results of TestJob - all we care about is if an exception was thrown
        // and if there was any, it is kept in Future until we call Future.get()
        future.get();
    }

    final NodeData cachedNodeData2 = hm.getNodeData("/test/website/foo/bar/generated-image");
    final InputStream res2 = cachedNodeData2.getStream();
    final ByteArrayOutputStream cachedOut2 = new ByteArrayOutputStream();
    IOUtils.copy(res2, cachedOut2);

    // assert all outs are the same
    for (int i = 1; i < outs2.length; i++) {
        // TODO assert they're all equals byte to byte to the source? or in size? can't as-is since we re-save..
        final byte[] a = outs2[i - 1].toByteArray();
        final byte[] b = outs2[i].toByteArray();
        assertTrue(a.length > 0);
        assertEquals("Different sizes (" + Math.abs(a.length - b.length) + " bytes diff.) with i=" + i,
                a.length, b.length);
        assertTrue("not equals for outs2/" + i, Arrays.equals(a, b));
        outs2[i - 1] = null;
    }
    assertTrue("failed comparing last thread's result with what we got from hierarchyManager",
            Arrays.equals(outs2[outs2.length - 1].toByteArray(), cachedOut2.toByteArray()));

    outs2[outs2.length - 1] = null;
}

From source file:com.cloud.hypervisor.kvm.resource.wrapper.LibvirtMigrateCommandWrapper.java

@Override
public Answer execute(final MigrateCommand command, final LibvirtComputingResource libvirtComputingResource) {
    final String vmName = command.getVmName();

    String result = null;//from ww  w.j  a v a 2 s  .  c  om

    List<InterfaceDef> ifaces = null;
    List<DiskDef> disks;

    Domain dm = null;
    Connect dconn = null;
    Domain destDomain = null;
    Connect conn = null;
    String xmlDesc = null;
    List<Ternary<String, Boolean, String>> vmsnapshots = null;

    try {
        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource
                .getLibvirtUtilitiesHelper();

        conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
        ifaces = libvirtComputingResource.getInterfaces(conn, vmName);
        disks = libvirtComputingResource.getDisks(conn, vmName);
        dm = conn.domainLookupByName(vmName);
        /*
        We replace the private IP address with the address of the destination host.
        This is because the VNC listens on the private IP address of the hypervisor,
        but that address is of course different on the target host.
                
        MigrateCommand.getDestinationIp() returns the private IP address of the target
        hypervisor. So it's safe to use.
                
        The Domain.migrate method from libvirt supports passing a different XML
        description for the instance to be used on the target host.
                
        This is supported by libvirt-java from version 0.50.0
                
        CVE-2015-3252: Get XML with sensitive information suitable for migration by using
                       VIR_DOMAIN_XML_MIGRATABLE flag (value = 8)
                       https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainXMLFlags
                
                       Use VIR_DOMAIN_XML_SECURE (value = 1) prior to v1.0.0.
         */
        final int xmlFlag = conn.getLibVirVersion() >= 1000000 ? 8 : 1; // 1000000 equals v1.0.0

        final String target = command.getDestinationIp();
        xmlDesc = dm.getXMLDesc(xmlFlag);
        xmlDesc = replaceIpForVNCInDescFile(xmlDesc, target);

        // delete the metadata of vm snapshots before migration
        vmsnapshots = libvirtComputingResource.cleanVMSnapshotMetadata(dm);

        Map<String, MigrateCommand.MigrateDiskInfo> mapMigrateStorage = command.getMigrateStorage();
        // migrateStorage is declared as final because the replaceStorage method may mutate mapMigrateStorage, but
        // migrateStorage's value should always only be associated with the initial state of mapMigrateStorage.
        final boolean migrateStorage = MapUtils.isNotEmpty(mapMigrateStorage);

        if (migrateStorage) {
            xmlDesc = replaceStorage(xmlDesc, mapMigrateStorage);
        }

        dconn = libvirtUtilitiesHelper
                .retrieveQemuConnection("qemu+tcp://" + command.getDestinationIp() + "/system");

        //run migration in thread so we can monitor it
        s_logger.info("Live migration of instance " + vmName + " initiated");
        final ExecutorService executor = Executors.newFixedThreadPool(1);
        final Callable<Domain> worker = new MigrateKVMAsync(libvirtComputingResource, dm, dconn, xmlDesc,
                migrateStorage, command.isAutoConvergence(), vmName, command.getDestinationIp());
        final Future<Domain> migrateThread = executor.submit(worker);
        executor.shutdown();
        long sleeptime = 0;
        while (!executor.isTerminated()) {
            Thread.sleep(100);
            sleeptime += 100;
            if (sleeptime == 1000) { // wait 1s before attempting to set downtime on migration, since I don't know of a VIR_DOMAIN_MIGRATING state
                final int migrateDowntime = libvirtComputingResource.getMigrateDowntime();
                if (migrateDowntime > 0) {
                    try {
                        final int setDowntime = dm.migrateSetMaxDowntime(migrateDowntime);
                        if (setDowntime == 0) {
                            s_logger.debug("Set max downtime for migration of " + vmName + " to "
                                    + String.valueOf(migrateDowntime) + "ms");
                        }
                    } catch (final LibvirtException e) {
                        s_logger.debug(
                                "Failed to set max downtime for migration, perhaps migration completed? Error: "
                                        + e.getMessage());
                    }
                }
            }
            if (sleeptime % 1000 == 0) {
                s_logger.info(
                        "Waiting for migration of " + vmName + " to complete, waited " + sleeptime + "ms");
            }

            // pause vm if we meet the vm.migrate.pauseafter threshold and not already paused
            final int migratePauseAfter = libvirtComputingResource.getMigratePauseAfter();
            if (migratePauseAfter > 0 && sleeptime > migratePauseAfter) {
                DomainState state = null;
                try {
                    state = dm.getInfo().state;
                } catch (final LibvirtException e) {
                    s_logger.info("Couldn't get VM domain state after " + sleeptime + "ms: " + e.getMessage());
                }
                if (state != null && state == DomainState.VIR_DOMAIN_RUNNING) {
                    try {
                        s_logger.info(
                                "Pausing VM " + vmName + " due to property vm.migrate.pauseafter setting to "
                                        + migratePauseAfter + "ms to complete migration");
                        dm.suspend();
                    } catch (final LibvirtException e) {
                        // pause could be racy if it attempts to pause right when vm is finished, simply warn
                        s_logger.info("Failed to pause vm " + vmName + " : " + e.getMessage());
                    }
                }
            }
        }
        s_logger.info("Migration thread for " + vmName + " is done");

        destDomain = migrateThread.get(10, TimeUnit.SECONDS);

        if (destDomain != null) {
            for (final DiskDef disk : disks) {
                libvirtComputingResource.cleanupDisk(disk);
            }
        }

    } catch (final LibvirtException e) {
        s_logger.debug("Can't migrate domain: " + e.getMessage());
        result = e.getMessage();
    } catch (final InterruptedException e) {
        s_logger.debug("Interrupted while migrating domain: " + e.getMessage());
        result = e.getMessage();
    } catch (final ExecutionException e) {
        s_logger.debug("Failed to execute while migrating domain: " + e.getMessage());
        result = e.getMessage();
    } catch (final TimeoutException e) {
        s_logger.debug("Timed out while migrating domain: " + e.getMessage());
        result = e.getMessage();
    } catch (final IOException e) {
        s_logger.debug("IOException: " + e.getMessage());
        result = e.getMessage();
    } catch (final ParserConfigurationException e) {
        s_logger.debug("ParserConfigurationException: " + e.getMessage());
        result = e.getMessage();
    } catch (final SAXException e) {
        s_logger.debug("SAXException: " + e.getMessage());
        result = e.getMessage();
    } catch (final TransformerConfigurationException e) {
        s_logger.debug("TransformerConfigurationException: " + e.getMessage());
        result = e.getMessage();
    } catch (final TransformerException e) {
        s_logger.debug("TransformerException: " + e.getMessage());
        result = e.getMessage();
    } finally {
        try {
            if (dm != null && result != null) {
                // restore vm snapshots in case of failed migration
                if (vmsnapshots != null) {
                    libvirtComputingResource.restoreVMSnapshotMetadata(dm, vmName, vmsnapshots);
                }
            }
            if (dm != null) {
                if (dm.isPersistent() == 1) {
                    dm.undefine();
                }
                dm.free();
            }
            if (dconn != null) {
                dconn.close();
            }
            if (destDomain != null) {
                destDomain.free();
            }
        } catch (final LibvirtException e) {
            s_logger.trace("Ignoring libvirt error.", e);
        }
    }

    if (result != null) {
    } else {
        libvirtComputingResource.destroyNetworkRulesForVM(conn, vmName);
        for (final InterfaceDef iface : ifaces) {
            // We don't know which "traffic type" is associated with
            // each interface at this point, so inform all vif drivers
            final List<VifDriver> allVifDrivers = libvirtComputingResource.getAllVifDrivers();
            for (final VifDriver vifDriver : allVifDrivers) {
                vifDriver.unplug(iface);
            }
        }
    }

    return new MigrateAnswer(command, result == null, result, null);
}

From source file:com.mirth.connect.plugins.datapruner.DataPrunerTest.java

@Test
@Ignore/*from w  w w . j a  v  a2 s .c  om*/
public final void testConcurrency() throws Exception {
    /*
     * To run this concurrency test, you must setup a "reader" channel through the
     * administrator, that routes messages to other channels that will be pruned. Then specify
     * the ids of those channels below.
     */
    final String readerChannelId = "f7158274-8692-4e53-9d17-db732c3346b8";
    ExecutorService executor = Executors.newSingleThreadExecutor();
    TestUtils.startMirthServer(15000);

    DataPruner pruner = new DataPruner();
    pruner.setBlockSize(1);
    pruner.setStrategy(Strategy.INCLUDE_LIST);
    pruner.setRetryCount(0);

    TestUtils.deleteAllMessages(readerChannelId);
    TestUtils.deleteAllMessages("0831345e-bbe0-4d62-8f2d-c65280bd479b");
    TestUtils.deleteAllMessages("b2e28f1b-d867-435a-a5f6-3b33d5261e66");

    // send messages into the test channel on a separate thread
    Future<Void> future = executor.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            EngineController engineController = ControllerFactory.getFactory().createEngineController();
            logger.info("Sending messages");

            for (int i = 0; i < 100000; i++) {
                logger.info("sending message #" + i);
                engineController.dispatchRawMessage(readerChannelId,
                        new RawMessage(TestUtils.TEST_HL7_MESSAGE));
            }

            logger.info("Finished sending messages");
            return null;
        }
    });

    logger.info("Executing pruner");

    // run the pruner while messages are processing
    while (!future.isDone()) {
        pruner.run();
        Thread.sleep(2000);
    }

    logger.info("Test completed");
}