Example usage for java.util.concurrent.atomic AtomicBoolean AtomicBoolean

List of usage examples for java.util.concurrent.atomic AtomicBoolean AtomicBoolean

Introduction

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

Prototype

public AtomicBoolean(boolean initialValue) 

Source Link

Document

Creates a new AtomicBoolean with the given initial value.

Usage

From source file:io.pravega.client.stream.impl.ReaderGroupStateManager.java

void checkpoint(String checkpointName, PositionInternal lastPosition) throws ReinitializationRequiredException {
    AtomicBoolean reinitRequired = new AtomicBoolean(false);
    sync.updateState(state -> {/*from w ww.  j  ava  2  s.  c o  m*/
        if (!state.isReaderOnline(readerId)) {
            reinitRequired.set(true);
            return null;
        }
        return Collections.singletonList(
                new CheckpointReader(checkpointName, readerId, lastPosition.getOwnedSegmentsWithOffsets()));
    });
    if (reinitRequired.get()) {
        throw new ReinitializationRequiredException();
    }
}

From source file:com.datatorrent.stram.engine.GenericNodeTest.java

@SuppressWarnings("SleepWhileInLoop")
private void testDoubleCheckpointHandling(ProcessingMode processingMode) throws Exception {
    WindowGenerator windowGenerator = new WindowGenerator(new ScheduledThreadPoolExecutor(1, "WindowGenerator"),
            1024);/*from   w ww .  j a  v  a2  s.c o  m*/
    windowGenerator.setResetWindow(0L);
    windowGenerator.setFirstWindow(0L);
    windowGenerator.setWindowWidth(100);
    windowGenerator.setCheckpointCount(1, 0);

    GenericCheckpointOperator gco = new GenericCheckpointOperator();
    DefaultAttributeMap dam = new DefaultAttributeMap();
    dam.put(OperatorContext.APPLICATION_WINDOW_COUNT, 2);
    dam.put(OperatorContext.CHECKPOINT_WINDOW_COUNT, 2);
    dam.put(OperatorContext.PROCESSING_MODE, processingMode);

    final GenericNode in = new GenericNode(gco, new com.datatorrent.stram.engine.OperatorContext(0, dam, null));
    in.setId(1);

    TestSink testSink = new TestSink();

    in.connectInputPort("ip1", windowGenerator.acquireReservoir(String.valueOf(in.id), 1024));
    in.connectOutputPort("output", testSink);
    in.firstWindowMillis = 0;
    in.windowWidthMillis = 100;

    windowGenerator.activate(null);

    final AtomicBoolean ab = new AtomicBoolean(false);
    Thread t = new Thread() {
        @Override
        public void run() {
            ab.set(true);
            in.activate();
            in.run();
            in.deactivate();
        }
    };

    t.start();

    long startTime = System.currentTimeMillis();
    long endTime = 0;

    while (gco.numWindows < 3 && ((endTime = System.currentTimeMillis()) - startTime) < 5000) {
        Thread.sleep(50);
    }

    in.shutdown();
    t.join();

    windowGenerator.deactivate();

    Assert.assertFalse(gco.checkpointTwice);
    Assert.assertTrue("Timed out", (endTime - startTime) < 5000);
}

From source file:io.nats.client.ITClusterTest.java

@Test
public void testProperReconnectDelay() throws Exception {
    try (NatsServer s1 = runServerOnPort(1222)) {
        Options opts = new Options.Builder(defaultOptions()).dontRandomize().build();
        opts.servers = Nats.processUrlArray(testServers);

        final CountDownLatch latch = new CountDownLatch(1);
        opts.disconnectedCb = new DisconnectedCallback() {
            public void onDisconnect(ConnectionEvent event) {
                event.getConnection().setDisconnectedCallback(null);
                latch.countDown();//from   w ww .  ja  v  a  2s. c om
            }
        };

        final AtomicBoolean ccbCalled = new AtomicBoolean(false);
        opts.closedCb = new ClosedCallback() {
            public void onClose(ConnectionEvent event) {
                ccbCalled.set(true);
            }
        };

        try (Connection c = opts.connect()) {
            assertFalse(c.isClosed());

            s1.shutdown();
            // wait for disconnect
            assertTrue("Did not receive a disconnect callback message", await(latch, 2, TimeUnit.SECONDS));

            // Wait, want to make sure we don't spin on reconnect to non-existent servers.
            sleep(1, TimeUnit.SECONDS);

            assertFalse("Closed CB was triggered, should not have been.", ccbCalled.get());
            assertEquals("Wrong state: " + c.getState(), c.getState(), RECONNECTING);
        }
    }
}

From source file:de.acosix.alfresco.site.hierarchy.repo.integration.ManagementViaWebScriptsTest.java

protected void checkSiteInTopLevelSites(final WebTarget webTarget, final Object ticket,
        final String siteShortName, final boolean expectation) {
    final TopLevelSites topLevelSites = webTarget.path("/acosix/api/sites/topLevelSites")
            .queryParam("alf_ticket", ticket).request(MediaType.APPLICATION_JSON).get(TopLevelSites.class);

    Assert.assertNotNull("List of top-level sites should never be null", topLevelSites.getSites());
    if (expectation) {
        Assert.assertFalse("List of top-level sites should not be empty", topLevelSites.getSites().isEmpty());
    }/*w  ww .  j  a  v  a  2 s  .c om*/

    final AtomicBoolean containsSite = new AtomicBoolean(false);
    topLevelSites.getSites().forEach(site -> {
        if (site.getShortName().equals(siteShortName)) {
            containsSite.set(true);
        }
    });
    Assert.assertEquals("Site top-level status listing does not match expectation", expectation,
            containsSite.get());
}

From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java

private static HeliosData loadHelios() throws IOException {
    System.out.println("Finding Helios implementation");

    HeliosData data = new HeliosData();

    boolean needsToDownload = !IMPL_FILE.exists();
    if (!needsToDownload) {
        try (JarFile jarFile = new JarFile(IMPL_FILE)) {
            ZipEntry entry = jarFile.getEntry("META-INF/MANIFEST.MF");
            if (entry == null) {
                needsToDownload = true;/* w w  w  .j a  v  a2 s  .c  om*/
            } else {
                Manifest manifest = new Manifest(jarFile.getInputStream(entry));
                String ver = manifest.getMainAttributes().getValue("Implementation-Version");
                try {
                    data.buildNumber = Integer.parseInt(ver);
                    data.version = manifest.getMainAttributes().getValue("Version");
                    data.mainClass = manifest.getMainAttributes().getValue("Main-Class");
                } catch (NumberFormatException e) {
                    needsToDownload = true;
                }
            }
        } catch (IOException e) {
            needsToDownload = true;
        }
    }
    if (needsToDownload) {
        URL latestJar = new URL(LATEST_JAR);
        System.out.println("Downloading latest Helios implementation");

        FileOutputStream out = new FileOutputStream(IMPL_FILE);
        HttpURLConnection connection = (HttpURLConnection) latestJar.openConnection();
        if (connection.getResponseCode() == 200) {
            int contentLength = connection.getContentLength();
            if (contentLength > 0) {
                InputStream stream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int amnt;
                AtomicInteger total = new AtomicInteger();
                AtomicBoolean stop = new AtomicBoolean(false);

                Thread progressBar = new Thread() {
                    public void run() {
                        JPanel panel = new JPanel();
                        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

                        JLabel label = new JLabel();
                        label.setText("Downloading latest Helios build");
                        panel.add(label);

                        GridLayout layout = new GridLayout();
                        layout.setColumns(1);
                        layout.setRows(3);
                        panel.setLayout(layout);
                        JProgressBar pbar = new JProgressBar();
                        pbar.setMinimum(0);
                        pbar.setMaximum(100);
                        panel.add(pbar);

                        JTextArea textArea = new JTextArea(1, 3);
                        textArea.setOpaque(false);
                        textArea.setEditable(false);
                        textArea.setText("Downloaded 00.00MB/00.00MB");
                        panel.add(textArea);

                        JFrame frame = new JFrame();
                        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                        frame.setContentPane(panel);
                        frame.pack();
                        frame.setLocationRelativeTo(null);
                        frame.setVisible(true);

                        while (!stop.get()) {
                            SwingUtilities.invokeLater(
                                    () -> pbar.setValue((int) (100.0 * total.get() / contentLength)));

                            textArea.setText("Downloaded " + bytesToMeg(total.get()) + "MB/"
                                    + bytesToMeg(contentLength) + "MB");
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException ignored) {
                            }
                        }
                        frame.dispose();
                    }
                };
                progressBar.start();

                while ((amnt = stream.read(buffer)) != -1) {
                    out.write(buffer, 0, amnt);
                    total.addAndGet(amnt);
                }
                stop.set(true);
                return loadHelios();
            } else {
                throw new IOException("Content-Length set to " + connection.getContentLength());
            }
        } else if (connection.getResponseCode() == 404) { // Most likely bootstrapper is out of date
            throw new RuntimeException("Bootstrapper out of date!");
        } else {
            throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());
        }
    }

    return data;
}

From source file:eu.esdihumboldt.hale.ui.service.instance.internal.orient.OrientInstanceService.java

/**
 * Perform the transformation/*  w  w  w  . j av a 2s  .c  om*/
 * 
 * @return if the transformation was successful
 */
protected boolean performTransformation() {
    final TransformationService ts = getTransformationService();
    if (ts == null) {
        log.userError("No transformation service available");
        return false;
    }

    final AtomicBoolean transformationFinished = new AtomicBoolean(false);
    final AtomicBoolean transformationCanceled = new AtomicBoolean(false);
    IRunnableWithProgress op = new IRunnableWithProgress() {

        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                Alignment alignment = getAlignmentService().getAlignment();
                if (alignment.getActiveTypeCells().isEmpty()) {
                    // early exit if there are no type relations
                    return;
                }

                // determine if there are any active type cells w/o source
                boolean transformEmpty = false;
                for (Cell cell : alignment.getActiveTypeCells()) {
                    if (cell.getSource() == null || cell.getSource().isEmpty()) {
                        transformEmpty = true;
                        break;
                    }
                }

                InstanceCollection sources = getInstances(DataSet.SOURCE);
                if (!transformEmpty && sources.isEmpty()) {
                    return;
                }

                HaleOrientInstanceSink sink = new HaleOrientInstanceSink(transformed, true);
                TransformationReport report;
                ATransaction trans = log.begin("Instance transformation");
                try {
                    report = ts.transform(alignment, sources, sink, HaleUI.getServiceProvider(),
                            new ProgressMonitorIndicator(monitor));

                    // publish report
                    ReportService rs = PlatformUI.getWorkbench().getService(ReportService.class);
                    rs.addReport(report);
                } finally {
                    try {
                        sink.close();
                    } catch (IOException e) {
                        // ignore
                    }
                    trans.end();
                }
            } finally {
                // remember if canceled
                if (monitor.isCanceled()) {
                    transformationCanceled.set(true);
                }

                // transformation finished
                transformationFinished.set(true);
            }
        }

    };

    try {
        ThreadProgressMonitor.runWithProgressDialog(op, ts.isCancelable());
    } catch (Throwable e) {
        log.error("Error starting transformation process", e);
    }

    // wait for transformation to complete
    HaleUI.waitFor(transformationFinished);

    return !transformationCanceled.get();
}

From source file:brooklyn.networking.cloudstack.legacy.LegacyJcloudsCloudstackSubnetLocation.java

@Override
protected JcloudsSshMachineLocation createJcloudsSshMachineLocation(ComputeService computeService,
        NodeMetadata node, Optional<Template> template, LoginCredentials userCredentials,
        HostAndPort managementHostAndPort, ConfigBag setup) throws IOException {
    String subnetSpecificHostname = null;
    String vmHostname = managementHostAndPort.getHostText();
    String sshHost = vmHostname;/*from  w  w w .  ja  v a 2s.  c  o  m*/
    Integer sshPort = null;
    PortForwardManager pfw = null;
    String publicIpId = null;

    final String serviceNetworkId = getConfig(CLOUDSTACK_SERVICE_NETWORK_ID);
    boolean portForwardingMode = Strings.isBlank(serviceNetworkId);
    LOG.debug("creating subnet JcloudsSshMachineLocation -- port forwarding={}, node={}",
            new Object[] { node, portForwardingMode });
    if (!portForwardingMode) {
        LOG.debug(
                "Using service network for Brooklyn access - service network ID is {} - searching for NIC connected to this network",
                serviceNetworkId);

        CloudStackApi cloudStackApi = getComputeService().getContext().unwrapApi(CloudStackApi.class);
        VirtualMachineApi vmClient = cloudStackApi.getVirtualMachineApi();
        VirtualMachine vm = vmClient.getVirtualMachine(node.getProviderId());

        Iterable<NIC> allNics = vm.getNICs();
        Predicate<NIC> isServiceNetwork = new Predicate<NIC>() {
            @Override
            public boolean apply(@Nullable NIC input) {
                return input != null && serviceNetworkId.equals(input.getNetworkId());
            }
        };
        Optional<NIC> serviceNic = Iterables.tryFind(allNics, isServiceNetwork);
        Iterable<NIC> otherNics = Iterables.filter(allNics, Predicates.not(isServiceNetwork));

        checkState(serviceNic.isPresent(),
                "unable to identify NIC connected to service network " + serviceNetworkId);
        String ipAddress = serviceNic.get().getIPAddress();
        checkState(Strings.isNonBlank(ipAddress),
                "no IP address on the NIC connected to service network " + serviceNetworkId);

        checkState(!Iterables.isEmpty(otherNics), "VM needs another NIC, in addition to the service network");
        // NIC anotherNic = Iterables.get(otherNics, 0);

        sshHost = ipAddress;
        sshPort = 22;
    } else {
        pfw = getRequiredConfig(PORT_FORWARDING_MANAGER);
        publicIpId = getRequiredConfig(CLOUDSTACK_TIER_PUBLIC_IP_ID);
        Cidr cidr = getConfig(MANAGEMENT_ACCESS_CIDR);

        // others, besides 22!
        int privatePort = 22;
        int publicPort = pfw.acquirePublicPort(publicIpId);

        systemCreatePortForwarding(cidr, publicPort, node, privatePort);

        sshPort = publicPort;
        sshHost = checkNotNull(pfw.getPublicIpHostname(publicIpId), "No ip recorded for id %s", publicIpId);
    }
    LOG.info("Created VM in " + this + " in subnet at " + node + ", ssh accessible via " + sshHost + ":"
            + sshPort);

    // and wait for it to be reachable

    LOG.debug("  waiting for new VM " + node + " in " + this + " to be port reachable on " + sshHost + ":"
            + sshPort);
    boolean isReachable = NetworkMultiAddressUtils2.isAccessible(sshHost, sshPort,
            TimeUnit.MINUTES.toMillis(15));
    if (!isReachable) {
        throw new IllegalStateException("Unable to contact forwarded SSH port for new VM " + node + " in "
                + this + " on " + sshHost + ":" + sshPort);
    }

    if (!NetworkMultiAddressUtils2.isResolveable(vmHostname)) {
        String oldHostname = vmHostname;
        vmHostname = Iterables.getFirst(Iterables.concat(node.getPublicAddresses(), node.getPrivateAddresses()),
                null);
        LOG.info("Renaming unresolvable hostname " + oldHostname + " to " + vmHostname);
    }

    // "public hostname" might be different
    // - sometimes it is not pingable from brooklyn (making sensors hard)
    // - sometimes furthest is the public one, we might want it
    //   (eg if we are in different 10.x subnet - closest not always accessible)
    //   or we might want nearest (if public is not accessible);
    //   and also consider we are on /16 subnet with host, host has another 10.x/8 address, but no public address;
    //   ie furthest might be inaccessible for other reasons
    // TODO i think the "right" way to do this is to have a pluggable "address chooser" ?

    LOG.debug("  vmHostname: " + vmHostname);

    // supply forwarded host and port
    Map<String, Object> sshConfig = extractSshConfig(setup, node);
    sshConfig.put(SshMachineLocation.SSH_HOST.getName(), sshHost);
    if (sshPort != null)
        sshConfig.put(SshMachineLocation.SSH_PORT.getName(), sshPort);

    if (LOG.isDebugEnabled()) {
        LOG.debug(
                "creating JcloudsSshMachineLocation in subnet {}, service network {}, for {}@{} for {} with {}",
                new Object[] { getRequiredConfig(CLOUDSTACK_SUBNET_NETWORK_ID),
                        getConfig(CLOUDSTACK_SERVICE_NETWORK_ID), userCredentials.getUser(), vmHostname,
                        setup.getDescription(), Sanitizer.sanitize(sshConfig) });
    }

    final JcloudsSshMachineLocation l = new AbstractJcloudsSubnetSshMachineLocation(
            MutableMap.builder().put("address", Networking.getInetAddressWithFixedName(vmHostname))
                    .put("displayName", vmHostname).put("user", userCredentials.getUser())
                    // don't think "config" does anything
                    .putAll(sshConfig).put("config", sshConfig).put("jcloudsParent", this)
                    .put(SshMachineLocation.PASSWORD, userCredentials.getOptionalPassword().orNull())
                    .put(SshMachineLocation.PRIVATE_KEY_DATA, userCredentials.getOptionalPrivateKey().orNull())
                    .put("node", node).put("template", template.orNull()).put("port", sshPort)
                    .put(CALLER_CONTEXT, setup.get(CALLER_CONTEXT)).build(),
            this, node) {
        @Override
        public HostAndPort getSocketEndpointFor(Cidr accessor, int privatePort) {
            return getPortForwardingTo(accessor, this, privatePort);
        }
    };
    l.init();
    getManagementContext().getLocationManager().manage(l);

    l.config().set(SUBNET_HOSTNAME_CONFIG, subnetSpecificHostname);
    l.config().set(VM_IDENTIFIER, node.getId());

    if (portForwardingMode) {
        // record port 22 forwarding
        pfw.associate(publicIpId, sshPort, l, 22);
    }

    LOG.debug("  waiting for new VM {} in {} to be SSH reachable on {}:{}",
            new Object[] { node, this, sshHost, sshPort });
    final AtomicBoolean isActive = new AtomicBoolean(false);
    Repeater.create().repeat(new Runnable() {
        @Override
        public void run() {
            try {
                int rc = l.execCommands("test accessibility", ImmutableList.of("hostname"));
                isActive.set(rc == 0);
            } catch (Throwable t) {
                isActive.set(false);
            }
        }
    }).every(Duration.FIVE_SECONDS).until(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return isActive.get();
        }
    }).limitTimeTo(Duration.FIVE_MINUTES).run();
    LOG.debug("  waited  for new VM {} in {} to be SSH reachable on {}:{}, result={}",
            new Object[] { node, this, sshHost, sshPort, isActive.get() });

    OperatingSystem operatingSystem = l.getNode().getOperatingSystem();
    if (operatingSystem != null) {
        OsFamily family = operatingSystem.getFamily();
        LOG.info("VM {}: OS family is {}", new Object[] { node, family });
        if (family != OsFamily.WINDOWS && family != OsFamily.UNRECOGNIZED) {
            LOG.warn("VM {}: disabling iptables", new Object[] { node });
            l.execScript(MutableMap.of(SshTool.PROP_ALLOCATE_PTY.getName(), true), "disabling requiretty",
                    Arrays.asList(BashCommands.dontRequireTtyForSudo()));
            l.execScript("disabling iptables",
                    Arrays.asList("sudo /etc/init.d/iptables stop", "sudo chkconfig iptables off"));
        } else {
            LOG.warn("VM {}: NOT disabling iptables because OS family is {}", new Object[] { node, family });
        }
    } else {
        LOG.warn("VM {}: NOT disabling iptables because OS is not detected", new Object[] { node });
    }

    String setupScript = setup.get(JcloudsLocationConfig.CUSTOM_MACHINE_SETUP_SCRIPT_URL);
    if (Strings.isNonBlank(setupScript)) {
        String setupVarsString = setup.get(JcloudsLocationConfig.CUSTOM_MACHINE_SETUP_SCRIPT_VARS);
        Map<String, String> substitutions = (setupVarsString != null)
                ? Splitter.on(",").withKeyValueSeparator(":").split(setupVarsString)
                : ImmutableMap.<String, String>of();
        String scriptContent = ResourceUtils.create(this).getResourceAsString(setupScript);
        String script = TemplateProcessor.processTemplateContents(scriptContent, substitutions);
        l.execScript(MutableMap.of(SshTool.PROP_ALLOCATE_PTY.getName(), true), "disabling requiretty",
                Arrays.asList(BashCommands.dontRequireTtyForSudo()));
        l.execCommands("Customizing node " + this, ImmutableList.of(script));
    }

    return l;
}

From source file:eu.europa.ec.markt.dss.validation102853.pades.PAdESSignature.java

private boolean hasDSSDictionary() {
    boolean hasDSSDictionary;
    final PDFSignatureService pdfTimestampSignatureService = PdfObjFactory.getInstance()
            .newTimestampSignatureService();
    try {//from   w  w w.  j a  v a  2 s .  co m
        final AtomicBoolean atomicHasDSSDictionnary = new AtomicBoolean(false);
        pdfTimestampSignatureService.validateSignatures(document.openStream(),
                new SignatureValidationCallback() {
                    @Override
                    public void validate(PdfDict catalog, PdfDict outerCatalog, X509Certificate signingCert,
                            Date signingDate, Certificate[] certs, PdfDict signatureDictionary,
                            PdfSignatureInfo pk) {
                        PdfDict _catalog = outerCatalog != null ? outerCatalog : pdfCatalog;
                        if (_catalog != null) {
                            atomicHasDSSDictionnary.set((getCertificateSource() != null)
                                    && (getCertificateSource().getCertificates() != null)
                                    && (!getCertificateSource().getCertificates().isEmpty()));
                        }
                    }
                });
        hasDSSDictionary = atomicHasDSSDictionnary.get();
    } catch (IOException e) {
        throw new DSSException(e);
    } catch (SignatureException e) {
        throw new DSSException(e);
    }
    return hasDSSDictionary;
}

From source file:io.nats.client.ITClusterTest.java

@Test
public void testProperFalloutAfterMaxAttempts() throws Exception {
    Options opts = new Options.Builder(defaultOptions()).dontRandomize().maxReconnect(5)
            .reconnectWait(25, TimeUnit.MILLISECONDS).build();
    opts.servers = Nats.processUrlArray(testServers);

    final CountDownLatch dcLatch = new CountDownLatch(1);
    opts.disconnectedCb = new DisconnectedCallback() {
        public void onDisconnect(ConnectionEvent event) {
            dcLatch.countDown();// w w  w  .ja  v a  2  s.c  o m
        }
    };

    final AtomicBoolean closedCbCalled = new AtomicBoolean(false);
    final CountDownLatch ccLatch = new CountDownLatch(1);
    opts.closedCb = new ClosedCallback() {
        public void onClose(ConnectionEvent event) {
            closedCbCalled.set(true);
            ccLatch.countDown();
        }
    };

    try (NatsServer s1 = runServerOnPort(1222)) {
        try (Connection c = opts.connect()) {
            s1.shutdown();

            // wait for disconnect
            assertTrue("Did not receive a disconnect callback message", await(dcLatch, 2, TimeUnit.SECONDS));

            // Wait for ClosedCB
            assertTrue("Did not receive a closed callback message", await(ccLatch, 2, TimeUnit.SECONDS));

            // Make sure we are not still reconnecting.
            assertTrue("Closed CB was not triggered, should have been.", closedCbCalled.get());

            // Expect connection to be closed...
            assertTrue("Wrong status: " + c.getState(), c.isClosed());
        }
    }
}

From source file:com.buaa.cfs.utils.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;/*from www.j a v a 2s .  com*/
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(
            new InputStreamReader(process.getErrorStream(), Charset.defaultCharset()));
    BufferedReader inReader = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.defaultCharset()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    } catch (OutOfMemoryError oe) {
        LOG.error("Caught " + oe + ". One possible reason is that ulimit"
                + " setting of 'max user processes' is too low. If so, do"
                + " 'ulimit -u <largerNum>' and try again.");
        throw oe;
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        // make sure that the error thread exits
        joinThread(errThread);
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled.  the stream draining thread will attempt to
            // drain that fd!!  it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            //      issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
            joinThread(errThread);
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = Time.monotonicNow();
    }
}