Example usage for java.lang Thread setName

List of usage examples for java.lang Thread setName

Introduction

In this page you can find the example usage for java.lang Thread setName.

Prototype

public final synchronized void setName(String name) 

Source Link

Document

Changes the name of this thread to be equal to the argument name .

Usage

From source file:com.microsoft.tfs.util.process.ProcessRunner.java

/**
 * Starts another process to run the commands this runner was constructed
 * with. Blocks until the process exits or {@link #interrupt()} is invoked.
 *
 * @see Runnable#run()/*from w  ww  .j  a v a2s .  c o m*/
 */
@Override
public void run() {
    synchronized (this) {
        if (state != ProcessRunnerState.NEW) {
            throw new IllegalStateException("Can only run a ProcessRunner once"); //$NON-NLS-1$
        }
    }

    /*
     * If the commands were empty, we can skip the process creation which
     * may be heavy on some platforms and simply report a success.
     */
    if (commands.length == 0) {
        synchronized (this) {
            exitCode = 0;
            state = ProcessRunnerState.COMPLETED;
        }

        notifyTerminalState();
        return;
    }

    try {
        synchronized (this) {
            process = Runtime.getRuntime().exec(commands, environment, workingDirectory);
            state = ProcessRunnerState.RUNNING;
        }
    } catch (final IOException e) {
        synchronized (this) {
            error = e;
            state = ProcessRunnerState.EXEC_FAILED;
        }

        notifyTerminalState();
        return;
    }

    /*
     * If we do not pump (read) the child process's streams (standard out
     * and standard error), Windows will cause the child to block if it
     * writes more than a small amount of output (512 bytes or chars [not
     * sure which] in our testing).
     *
     * If the user of this runner is interested in the child's output, we
     * have to service the streams in other threads in order to prevent
     * becoming blind to an interruption delivered to this thread.
     * Specifically, reading from these streams is a blocking task, and
     * there is no way for the user to interrupt us while we block. If we
     * launch other threads, we arrive at process.waitFor() quickly in this
     * thread and can accept the interruption, then interrupt the readers.
     */

    final Thread outputReaderThread = new Thread(
            new ProcessOutputReader(process.getInputStream(), capturedStandardOutput));

    String messageFormat = "Standard Output Reader {0}"; //$NON-NLS-1$
    String message = MessageFormat.format(messageFormat, Long.toString(getNewThreadID()));
    outputReaderThread.setName(message);
    outputReaderThread.start();

    messageFormat = "Started IO waiter thread '{0}'"; //$NON-NLS-1$
    message = MessageFormat.format(messageFormat, outputReaderThread.getName());
    log.debug(message);

    final Thread errorReaderThread = new Thread(
            new ProcessOutputReader(process.getErrorStream(), capturedStandardError));

    messageFormat = "Standard Error Reader {0}"; //$NON-NLS-1$
    message = MessageFormat.format(messageFormat, Long.toString(getNewThreadID()));
    errorReaderThread.setName(message);
    errorReaderThread.start();

    messageFormat = "Started IO waiter thread '{0}'"; //$NON-NLS-1$
    message = MessageFormat.format(messageFormat, errorReaderThread.getName());
    log.debug(message);

    int ret;
    try {
        /*
         * We must not hold the lock on this while we wait on the child, or
         * we could not be interrupted.
         */
        ret = process.waitFor();
    } catch (final InterruptedException e) {
        log.debug("Normal interruption, interrupting all IO readers"); //$NON-NLS-1$

        /*
         * We must join on all IO readers before entering a terminal state
         * to prevent the reader threads from later writing to their
         * streams. This method also performs the immediate interrupt.
         *
         * Ignore if there was an error joining because we just want to
         * terminate as INTERRUPTED anyway.
         */
        joinReaders(new Thread[] { outputReaderThread, errorReaderThread }, true);

        /*
         * This is the normal abort scenario. No exit code is available and
         * no error occurred.
         */
        synchronized (this) {
            state = ProcessRunnerState.INTERRUPTED;
        }

        notifyTerminalState();
        return;
    }

    /*
     * If we launched output reader threads, we have to wait for them to
     * complete here. This is usually a short wait because once we're this
     * far, process.waitFor() has finished so the readers will be reaching
     * the end of their input streams soon (and terminating).
     *
     * If we get an error back from the join, we want to consider this
     * entire runner INTERRUPTED because we can't trust the output streams
     * to have the entire contents of the process.
     */

    if (joinReaders(new Thread[] { outputReaderThread, errorReaderThread }, false) == false) {
        log.error("Error joining IO reader threads, setting INTERRUPTED"); //$NON-NLS-1$

        synchronized (this) {
            state = ProcessRunnerState.INTERRUPTED;
        }

        notifyTerminalState();
        return;
    }

    /*
     * Now that we have joined the IO reader threads, we can close the close
     * the streams in order to prevent Java from leaking the handles.
     */

    try {
        process.getOutputStream().close();
        process.getInputStream().close();
        process.getErrorStream().close();
    } catch (final IOException e) {
        /*
         * This exception is from Stream.close().
         *
         * A failure to configure the output streams is a critical error and
         * should be treated as a failure to launch the process. Setting
         * different state could cause the user to trust that his process
         * which returned a 0 exit code also printed no error text when it
         * actually did (and therefore failed).
         */

        log.error("Error closing child process's output streams after join, setting INTERRUPTED", e); //$NON-NLS-1$

        synchronized (this) {
            state = ProcessRunnerState.INTERRUPTED;
        }

        notifyTerminalState();
        return;
    }

    synchronized (this) {
        exitCode = ret;
        state = ProcessRunnerState.COMPLETED;
    }

    notifyTerminalState();
}

From source file:com.google.dart.tools.core.DartCore.java

/**
 * Answer the unique project manager used for analysis of anything in the workspace.
 * /*from ww  w.  j a  va  2  s  .  c o  m*/
 * @return the manager (not {@code null})
 */
public static ProjectManager getProjectManager() {
    synchronized (projectManagerLock) {
        if (projectManager == null) {
            // start index
            final Index index;
            {
                File stateDir = getPlugin().getStateLocation().toFile();
                File indexDir = new File(stateDir, "index");
                indexDir.mkdirs();
                IndexStore indexStore = IndexFactory.newFileIndexStore(indexDir);
                index = IndexFactory.newIndex(indexStore);
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        index.run();
                    }
                };
                thread.setName("Index Thread");
                thread.setDaemon(true);
                thread.start();
            }
            // create ProjectManagerImpl
            projectManager = new ProjectManagerImpl(ResourcesPlugin.getWorkspace().getRoot(),
                    DartSdkManager.getManager().getSdk(), DartSdkManager.getManager().getSdkContextId(), index,
                    DartIgnoreManager.getInstance());
        }
    }
    return projectManager;
}

From source file:org.apache.hadoop.contrib.bkjournal.TestBookKeeperJournalManager.java

/**
 * Sleep a bookie until I count down the latch
 *
 * @param latch// w w w.j  av  a 2  s.  c  o  m
 *          Latch to wait on
 * @param bookie
 *          bookie server
 * @throws Exception
 */
private void sleepBookie(final CountDownLatch l, final BookieServer bookie) throws Exception {

    Thread sleeper = new Thread() {
        public void run() {
            try {
                bookie.suspendProcessing();
                l.await(60, TimeUnit.SECONDS);
                bookie.resumeProcessing();
            } catch (Exception e) {
                LOG.error("Error suspending bookie", e);
            }
        }
    };
    sleeper.setName("BookieServerSleeper-" + bookie.getBookie().getId());
    sleeper.start();
}

From source file:com.edgenius.wiki.webapp.action.BaseAction.java

/**
 * Ugly, but 2 Action class need it....//  ww  w  .  jav a2  s. co m
 * @param listener
 * @param indexService
 */
protected void rebuildIndexes(final IndexRebuildListener listener, final IndexServiceImpl indexService) {
    //this method only clean index files so far...
    indexService.cleanIndexes(listener);

    final String uuid = UUID.randomUUID().toString();
    //I don't know how invoke HibernateInceptor inside IndexServiceImpl.rebuildIndex() threads, so I copy 
    //them into here, so that each rebuild*() thread will be surround  HibernateInceptor to avoid lazy loading problem
    //see http://forum.springframework.org/showthread.php?p=200379#post200379
    Thread t1 = new Thread(new Runnable() {
        public void run() {
            try {
                //Some page render need space read permission, such as PageIndex needs PageService.getPageTree() method.
                securityService.proxyLoginAsSystemAdmin();
                ((IndexServiceImpl) indexService).rebuildPageIndex();
            } catch (Exception e) {
                log.warn("Page index rebuid complete with error", e);
            } finally {
                securityService.proxyLogout();
            }
            listener.indexComplete(IndexRebuildListener.PAGE);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.PAGE);
        }

    });
    t1.setName("Rebuild page index");
    t1.setDaemon(true);
    t1.start();

    Thread t2 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildCommentIndex();
            listener.indexComplete(IndexRebuildListener.COMMENT);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.COMMENT);
        }
    });
    t2.setDaemon(true);
    t2.setName("Rebuild comment index");
    t2.start();

    Thread t3 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildSpaceIndex();
            listener.indexComplete(IndexRebuildListener.SPACE);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.SPACE);
        }
    });
    t3.setDaemon(true);
    t3.setName("Rebuild space index");
    t3.start();

    Thread t4 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildUserIndex();
            listener.indexComplete(IndexRebuildListener.USER);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.USER);

        }
    });
    t4.setDaemon(true);
    t4.setName("Rebuild user index");
    t4.start();

    Thread t5 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildRoleIndex();
            listener.indexComplete(IndexRebuildListener.ROLE);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.ROLE);
        }
    });
    t5.setDaemon(true);
    t5.setName("Rebuild role index");
    t5.start();

    Thread t6 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildPageTagIndex();
            listener.indexComplete(IndexRebuildListener.PTAG);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.PTAG);
        }
    });
    t6.setDaemon(true);
    t6.setName("Rebuild page tag index");
    t6.start();

    Thread t7 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildSpaceTagIndex();
            listener.indexComplete(IndexRebuildListener.STAG);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.STAG);
        }
    });
    t7.setDaemon(true);
    t7.setName("Rebuild space tag index");
    t7.start();

    Thread t8 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildAttachmentIndex();
            listener.indexComplete(IndexRebuildListener.ATTACHMENT);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.ATTACHMENT);
        }
    });
    t8.setDaemon(true);
    t8.setName("Rebuild attachment index");
    t8.start();

    Thread t9 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildWidgetIndex();
            listener.indexComplete(IndexRebuildListener.WIDGET);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.WIDGET);
        }
    });
    t9.setDaemon(true);
    t9.setName("Rebuild widget index");
    t9.start();
}

From source file:com.github.vatbub.tictactoe.Board.java

public void doTurn(Move move, boolean ignoreAI) {
    lastMove = move;//from w  w  w  . j a v a 2  s .c om

    if (getPlayerAt(move.getRow(), move.getColumn()) != null) {
        throw new IllegalStateException("Cell is already taken by a player");
    }

    this.setPlayerAt(move.getRow(), move.getColumn(), getCurrentPlayer());

    if (getOpponent(getCurrentPlayer()).getPlayerMode().equals(PlayerMode.internetHuman) && !ignoreAI) {
        KryoGameConnections.sendMove(move);
    }

    WinnerInfo winnerInfo = getWinner(move.getRow(), move.getColumn());
    if (winnerInfo.winningPlayer != null) {
        if (getGameEndCallback() != null) {
            getGameEndCallback().run(winnerInfo);
        }
        return;
    }

    currentPlayerProperty().set(getOpponent(getCurrentPlayer()));

    if (getCurrentPlayer().getPlayerMode().equals(PlayerMode.ai) && !ignoreAI) {
        final Board thisCopy = this;
        Thread aiWaitThread = new Thread(() -> {
            PrintStream nullPrintStream = new PrintStream(new NullOutputStream());
            while (Main.currentMainWindowInstance.isBlockedForInput()) {
                // wait
                nullPrintStream.println("Waiting...");
            }

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                FOKLogger.log(Board.class.getName(), Level.SEVERE, "An error occurred", e);
            }

            getCurrentPlayer().doAiTurn(thisCopy);
            Main.currentMainWindowInstance.updateCurrentPlayerLabel();
            Main.currentMainWindowInstance.renderRows();
        });
        aiWaitThread.setName("aiWaitThread");
        aiWaitThread.start();
    }
}

From source file:org.apache.hadoop.hdfs.server.balancerv2.DispatcherV2.java

public DispatcherV2(long maxNoPedingMoveIterations, long noPedingMoveSleepTime, long blockByteNum,
        long maxIterationTime, NameNodeConnector nnc, Set<String> includedNodes, Set<String> excludedNodes,
        long movedWinWidth, int moverThreads, int dispatcherThreads, int maxConcurrentMovesPerNode,
        Configuration conf) {/*w  w  w.j ava  2s  . c  o m*/
    this.nnc = nnc;
    this.excludedNodes = excludedNodes;
    this.includedNodes = includedNodes;
    this.movedBlocks = new MovedBlocks<StorageGroup>(movedWinWidth);
    this.blockByteNum = blockByteNum;
    this.maxIterationTime = maxIterationTime;
    this.maxNoPedingMoveIterations = maxNoPedingMoveIterations;
    this.noPedingMoveSleepTime = noPedingMoveSleepTime;
    LOG.info("noPedingMoveSleepTime:" + noPedingMoveSleepTime + ", maxIterationTime:" + maxIterationTime
            + ", maxNoPedingMoveIterations:" + maxNoPedingMoveIterations + ", blockByteNum: " + blockByteNum
            + ", maxConcurrentMovesPerNode:" + maxConcurrentMovesPerNode + ", dispatcherThreads:"
            + dispatcherThreads + ", moverThreads:" + moverThreads);
    this.cluster = NetworkTopology.getInstance(conf);

    this.moveExecutor = Executors.newFixedThreadPool(moverThreads, new Daemon.DaemonFactory() {
        private final AtomicInteger threadIndex = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = super.newThread(r);
            t.setName("balancerMoveBlock-" + threadIndex.getAndIncrement());
            return t;
        }
    });

    this.dispatchExecutor = dispatcherThreads == 0 ? null
            : Executors.newFixedThreadPool(dispatcherThreads, new Daemon.DaemonFactory() {
                private final AtomicInteger threadIndex = new AtomicInteger(0);

                @Override
                public Thread newThread(Runnable r) {
                    Thread t = super.newThread(r);
                    t.setName("balancerDispatch-" + threadIndex.getAndIncrement());
                    return t;
                }
            });

    this.maxConcurrentMovesPerNode = maxConcurrentMovesPerNode;

    this.saslClient = new SaslDataTransferClient(conf, DataTransferSaslUtil.getSaslPropertiesResolver(conf),
            TrustedChannelResolver.getInstance(conf), nnc.fallbackToSimpleAuth);
}

From source file:org.apache.nifi.registry.bootstrap.RunNiFiRegistry.java

public RunNiFiRegistry(final File bootstrapConfigFile, final boolean verbose) throws IOException {
    this.bootstrapConfigFile = bootstrapConfigFile;

    loggingExecutor = Executors.newFixedThreadPool(2, new ThreadFactory() {
        @Override//from w w w . j av a  2s . c om
        public Thread newThread(final Runnable runnable) {
            final Thread t = Executors.defaultThreadFactory().newThread(runnable);
            t.setDaemon(true);
            t.setName("NiFi logging handler");
            return t;
        }
    });
}

From source file:edu.ku.brc.services.biogeomancer.GeoCoordBGMProvider.java

public void processGeoRefData(final List<GeoCoordDataIFace> items,
        final GeoCoordProviderListenerIFace listenerArg, final String helpContextArg) {
    this.listener = listenerArg;
    this.helpContext = helpContextArg;

    UsageTracker.incrUsageCount("Tools.BioGeomancerData"); //$NON-NLS-1$

    log.info("Performing BioGeomancer lookup of selected records"); //$NON-NLS-1$

    // create a progress bar dialog to show the network progress
    final ProgressDialog progressDialog = new ProgressDialog(
            UIRegistry.getResourceString("GeoCoordBGMProvider.BIOGEOMANCER_PROGRESS"), false, true); // I18N //$NON-NLS-1$
    progressDialog.getCloseBtn().setText(getResourceString("CANCEL")); //$NON-NLS-1$
    progressDialog.setModal(true);// w  w  w  .ja v a  2  s .co m
    progressDialog.setProcess(0, items.size());

    // XXX Java 6
    //progressDialog.setIconImage( IconManager.getImage("AppIcon").getImage());

    // use a SwingWorker thread to do all of the work, and update the GUI when done
    final SwingWorker bgTask = new SwingWorker() {
        final JStatusBar statusBar = UIRegistry.getStatusBar();
        protected boolean cancelled = false;

        @Override
        public void interrupt() {
            super.interrupt();
            cancelled = true;
        }

        @SuppressWarnings("synthetic-access") //$NON-NLS-1$
        @Override
        public Object construct() {
            // perform the BG web service call ON all rows, storing results in the rows

            int progress = 0;

            for (GeoCoordDataIFace item : items) {
                if (cancelled) {
                    break;
                }

                // get the locality data
                String localityNameStr = item.getLocalityString();

                // get the geography data
                String country = item.getCountry();
                String state = item.getState();
                String county = item.getCounty();

                log.info("Making call to BioGeomancer service: " + localityNameStr); //$NON-NLS-1$
                String bgResults;
                BioGeomancerQuerySummaryStruct bgQuerySummary;
                try {
                    bgResults = BioGeomancer.getBioGeomancerResponse(item.getGeoCoordId().toString(), country,
                            state, county, localityNameStr);
                    bgQuerySummary = BioGeomancer.parseBioGeomancerResponse(bgResults);
                } catch (IOException ex1) {
                    String warning = getResourceString("GeoCoordBGMProvider.WB_BIOGEOMANCER_UNAVAILABLE"); //$NON-NLS-1$
                    statusBar.setWarningMessage(warning, ex1);
                    log.error("A network error occurred while contacting the BioGeomancer service", ex1); //$NON-NLS-1$

                    // update the progress bar UI and move on
                    progressDialog.setProcess(++progress);
                    continue;
                } catch (Exception ex2) {
                    UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(GeoCoordBGMProvider.class,
                            ex2);
                    // right now we'll simply blame this on BG
                    // in the future we might get more specific about this error
                    String warning = getResourceString("GeoCoordBGMProvider.WB_BIOGEOMANCER_UNAVAILABLE"); //$NON-NLS-1$
                    statusBar.setWarningMessage(warning, ex2);
                    log.warn("Failed to get result count from BioGeomancer respsonse", ex2); //$NON-NLS-1$

                    // update the progress bar UI and move on
                    progressDialog.setProcess(++progress);
                    continue;
                }

                // if there was at least one result, pre-cache a map for that result
                int resCount = bgQuerySummary.results.length;
                if (resCount > 0) {
                    final int rowNumber = item.getGeoCoordId();
                    final BioGeomancerQuerySummaryStruct summaryStruct = bgQuerySummary;
                    // create a thread to go grab the map so it will be cached for later use
                    Thread t = new Thread(new Runnable() {
                        public void run() {
                            try {
                                log.info("Requesting map of BioGeomancer results for workbench row " //$NON-NLS-1$
                                        + rowNumber);
                                BioGeomancer.getMapOfQuerySummary(summaryStruct, null);
                            } catch (Exception e) {
                                UsageTracker.incrHandledUsageCount();
                                edu.ku.brc.exceptions.ExceptionTracker.getInstance()
                                        .capture(GeoCoordBGMProvider.class, e);
                                log.warn("Failed to pre-cache BioGeomancer results map", e); //$NON-NLS-1$
                            }
                        }
                    });
                    t.setName("Map Pre-Caching Thread: row " + item.getGeoCoordId()); // I18N //$NON-NLS-1$
                    log.debug("Starting map pre-caching thread"); //$NON-NLS-1$
                    t.start();
                }

                // if we got at least one result...
                if (resCount > 0) {
                    item.setXML(bgResults);
                }

                // update the progress bar UI and move on
                progressDialog.setProcess(++progress);
            }

            return null;
        }

        @Override
        public void finished() {
            statusBar.setText(getResourceString("GeoCoordBGMProvider.BIOGEOMANCER_COMPLETED")); //$NON-NLS-1$

            if (!cancelled) {
                // hide the progress dialog
                progressDialog.setVisible(false);

                // find out how many records actually had results
                List<GeoCoordDataIFace> rowsWithResults = new Vector<GeoCoordDataIFace>();
                for (GeoCoordDataIFace row : items) {
                    if (row.getXML() != null) {
                        rowsWithResults.add(row);
                    }
                }

                // if no records had possible results...
                int numRecordsWithResults = rowsWithResults.size();
                if (numRecordsWithResults == 0) {
                    statusBar.setText(getResourceString("GeoCoordBGMProvider.NO_BG_RESULTS")); //$NON-NLS-1$
                    JOptionPane.showMessageDialog(UIRegistry.getTopWindow(),
                            getResourceString("GeoCoordBGMProvider.NO_BG_RESULTS"),
                            getResourceString("NO_RESULTS"), JOptionPane.INFORMATION_MESSAGE);
                    return;
                }

                if (listener != null) {
                    listener.aboutToDisplayResults();
                }

                // ask the user if they want to review the results
                String message = String.format(
                        getResourceString("GeoCoordBGMProvider.BGM_VIEW_RESULTS_CONFIRM"), //$NON-NLS-1$
                        String.valueOf(numRecordsWithResults));
                int userChoice = JOptionPane.showConfirmDialog(UIRegistry.getTopWindow(), message,
                        getResourceString("GeoCoordBGMProvider.CONTINUE"), JOptionPane.YES_NO_OPTION);//$NON-NLS-1$

                if (userChoice != JOptionPane.YES_OPTION) {
                    statusBar.setText(getResourceString("GeoCoordBGMProvider.BIOGEOMANCER_TERMINATED")); //$NON-NLS-1$
                    return;
                }

                displayBioGeomancerResults(rowsWithResults);
            }
        }
    };

    // if the user hits close, stop the worker thread
    progressDialog.getCloseBtn().addActionListener(new ActionListener() {
        @SuppressWarnings("synthetic-access") //$NON-NLS-1$
        public void actionPerformed(ActionEvent ae) {
            log.debug("Stopping the BioGeomancer service worker thread"); //$NON-NLS-1$
            bgTask.interrupt();
        }
    });

    log.debug("Starting the BioGeomancer service worker thread"); //$NON-NLS-1$
    bgTask.start();
    UIHelper.centerAndShow(progressDialog);
}

From source file:org.apache.nifi.controller.StandardFlowService.java

@Override
public void stop(final boolean force) {
    writeLock.lock();/*w w w  . j av a  2  s . co  m*/
    try {

        if (!isRunning()) {
            return;
        }

        running.set(false);

        if (clusterCoordinator != null) {
            final Thread shutdownClusterCoordinator = new Thread(new Runnable() {
                @Override
                public void run() {
                    clusterCoordinator.shutdown();
                }
            });
            shutdownClusterCoordinator.setDaemon(true);
            shutdownClusterCoordinator.setName("Shutdown Cluster Coordinator");
            shutdownClusterCoordinator.start();
        }

        if (!controller.isTerminated()) {
            controller.shutdown(force);
        }

        if (configuredForClustering && senderListener != null) {
            try {
                senderListener.stop();
            } catch (final IOException ioe) {
                logger.warn("Protocol sender/listener did not stop gracefully due to: " + ioe);
            }
        }

        final ScheduledExecutorService executorService = executor.get();
        if (executorService != null) {
            if (force) {
                executorService.shutdownNow();
            } else {
                executorService.shutdown();
            }

            boolean graceful;
            try {
                graceful = executorService.awaitTermination(gracefulShutdownSeconds, TimeUnit.SECONDS);
            } catch (final InterruptedException e) {
                graceful = false;
            }

            if (!graceful) {
                logger.warn("Scheduling service did not gracefully shutdown within configured "
                        + gracefulShutdownSeconds + " second window");
            }
        }
    } finally {
        writeLock.unlock();
    }
}

From source file:org.hyperledger.fabric.sdkintegration.End2endMTIT.java

public void runFabricTest(final SampleStore sampleStore) throws Exception {

    ////////////////////////////
    // Setup client

    //Create instance of client.
    HFClient client = HFClient.createNewInstance();

    client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());

    ////////////////////////////
    //Construct and run the channels
    final Collection<CompletableFuture<BlockEvent.TransactionEvent>> futures = new ArrayList<>(2);
    //  CompletableFuture<BlockEvent.TransactionEvent>[] ii = new CompletableFuture[2];
    SampleOrg sampleOrg1 = testConfig.getIntegrationTestsSampleOrg("peerOrg1");
    Channel fooChannel = constructChannel(FOO_CHANNEL_NAME, client, sampleOrg1);
    futures.add(installInstantiate(fooChannel, client, sampleOrg1));

    SampleOrg sampleOrg2 = testConfig.getIntegrationTestsSampleOrg("peerOrg2");
    Channel barChannel = constructChannel(BAR_CHANNEL_NAME, client, sampleOrg2);
    futures.add(installInstantiate(barChannel, client, sampleOrg2));

    final CompletableFuture<Void> voidCompletableFuture = CompletableFuture
            .allOf(futures.toArray(new CompletableFuture[futures.size()]));
    voidCompletableFuture.thenApply(avoid -> {

        ArrayList<Thread> threads = new ArrayList<>();
        TestPair[] testPairs = { new TestPair(fooChannel, sampleOrg1), new TestPair(barChannel, sampleOrg2) };

        for (int i = 0; i < WORKER_COUNT; ++i) {

            Thread thread = new Thread(new Worker(i, client, testPairs));
            thread.setName("TCW_" + i);
            thread.setDaemon(true);/*  ww w  .j av a  2  s. c om*/
            thread.start();

            threads.add(thread);

            try {
                Thread.sleep(random.nextInt(3000)); // stage them to be doing different tasks
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        threads.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        return null;

    }).get();

    //        voidCompletableFuture.thenApply(() -> futures.stream()
    //                .map(CompletableFuture::join)
    //                .collect(Collectors.toList())
    //        );
    //
    //        CompletableFuture<BlockEvent.TransactionEvent>.allOf (futures.toArray())
    //                .thenApply(() -> futures.stream()
    //                        .map(CompletableFuture::join)
    //                        .collect(Collectors.toList())
    //                );

    //        //let bar channel just shutdown so we have both scenarios.
    //
    //        out("\nTraverse the blocks for chain %s ", barChannel.getName());
    //
    //        blockWalker(client, barChannel);
    //
    //        assertFalse(barChannel.isShutdown());
    //        assertTrue(barChannel.isInitialized());

    out("That's all folks!");

}