Example usage for java.lang Thread join

List of usage examples for java.lang Thread join

Introduction

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

Prototype

public final void join() throws InterruptedException 

Source Link

Document

Waits for this thread to die.

Usage

From source file:de.whiledo.iliasdownloader2.swing.service.MainController.java

public static void showError(final Component parent, String description, final Throwable e) {
    String s = "";
    if (e instanceof IliasHTTPSException) {
        s = "<br><br>Die SSL Verbindung konnte nicht aufgebaut werden." + "<br>Sie benutzen Java Version "
                + System.getProperty("java.version") + "."
                + "<br>Fr einige SSL Verbindungen bentigen Sie <b>Java 1.8 oder hher.</b>"
                + "<br>Sie knnen Java hier herunterladen: http://java.com"
                + "<br><br>Alternativ knnen Sie in den Einstellungen beim Serverpfad https:// durch http:// ersetzen."
                + "<br><b>Das wird aber NICHT empfohlen, da Ihr Loginname und Ihr Passwort ungeschtzt bertragen werden.</b>";
    }/*  w w  w  .j a  v a 2  s  . co m*/

    description = description + s;

    JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    panel.add(new JLabel("<html>" + description + "</html>"));

    JButton b = new JButton("Details");
    b.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ev) {
            final JTextArea textarea = new JTextArea();
            val c = new CircularStream();

            Thread t = new Thread(new Runnable() {

                @Override
                public void run() {
                    e.printStackTrace(new PrintStream(c.getOutputStream()));
                    IOUtils.closeQuietly(c.getOutputStream());
                }
            });
            t.start();

            try {
                textarea.append(IOUtils.toString(c.getInputStream()));
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            try {
                t.join();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }

            JPanel p = new JPanel(new BorderLayout());
            p.add(new JLabel(e.getMessage()), BorderLayout.NORTH);

            JScrollPane scrollpane = new JScrollPane(textarea);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            p.add(scrollpane, BorderLayout.CENTER);
            p.setMaximumSize(new Dimension(screenSize.width / 2, screenSize.height / 2));
            p.setPreferredSize(new Dimension(screenSize.width / 2, screenSize.height / 2));
            p.setSize(new Dimension(screenSize.width / 2, screenSize.height / 2));

            JOptionPane.showMessageDialog(parent, p, "Fehlerdetails", JOptionPane.ERROR_MESSAGE);

        }
    });
    panel.add(b);

    JOptionPane.showMessageDialog(parent, panel, "Fehler", JOptionPane.ERROR_MESSAGE);
}

From source file:gov.nih.nci.firebird.proxy.PoolingHandlerTest.java

@Test
public void testPoolDepletion() throws InterruptedException {
    Provider<BaseClient> provider = new Provider<BaseClient>() {
        @Override// w ww. j a  v a 2  s  . c om
        public BaseClient get() {
            return new BaseClient();
        }
    };
    PoolingHandler handler = new PoolingHandler(provider, 3, 0);
    final ITestClient proxy = (ITestClient) Proxy.newProxyInstance(this.getClass().getClassLoader(),
            new Class<?>[] { ITestClient.class }, handler);

    for (int i = 0; i < 5; i++) {
        Thread t = new Thread() {
            @Override
            public void run() {
                proxy.block();
            }
        };
        t.start();
    }

    synchronized (threads) {
        while (threads.size() < 5) {
            threads.wait(500L);
        }
    }
    // all threads started
    assertEquals(0, handler.getPool().getNumIdle());
    assertEquals(5, handler.getPool().getNumActive());

    // let threads resume.
    synchronized (BaseClient.class) {
        BaseClient.class.notifyAll();
    }

    for (Thread t : threads) {
        t.join();
    }
    assertEquals(3, handler.getPool().getNumIdle());
}

From source file:eu.sisob.uma.NPL.Researchers.GateDataExtractorTask.java

/**
 *
 *///from ww  w.j  a v  a2 s.  c o m
@Override
public void executeTask() {
    if (getExecutorResource() != null) {

        TextMiningParserGateResearcher parser = null;
        DataRepository parserRepPrePro = null;
        RepositoryProcessedDataXML repXML = null;

        try {
            //Take parser and load input repository from CSV                    
            parser = (TextMiningParserGateResearcher) this.executorResource.getResource();
            parserRepPrePro = (DataRepository) parser.getRepOutput();
            repXML = (RepositoryProcessedDataXML) parser.getRepInput();

            List<MiddleData> mds = null;
            while ((mds = taskRepPrePro.getData(DataExchangeLiterals.ID_TEXTMININGPARSER_GATERESEARCHER, 100))
                    .size() > 0) {
                for (MiddleData md : mds)
                    parserRepPrePro.addData(md);
            }

            Thread th = null;
            UncaughtExceptionHandler he = new UncaughtExceptionHandler() {
                public Throwable e = null;

                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    occursUncaugthExceptionInGateProcess = true;
                    ProjectLogger.LOGGER.info("uncaughtException: " + e.getMessage());
                }
            };

            //Launch GATE parser     
            this.occursUncaugthExceptionInGateProcess = false;
            th = new Thread(parser);
            th.setUncaughtExceptionHandler(he);
            th.start();
            th.join();

            this.xml_doc_results = (Document) repXML.getDocXML().clone();

            // Augmented Information Block
            if (this.use_dataresolver && this.credentials_academic_trad_tables != null) {
                //Using data resolver "method 2", see the class for the heuristic

                try {
                    DataResearcherAugmentedInformation.resolveLocationOfEntities(xml_doc_results,
                            new LocationDataResolver_Method2(true, this.credentials_dataresolver));
                } catch (Exception ex) {
                    Logger.getRootLogger().error("Error resolving locator. " + ex.toString());
                }

            }

            // Augmented Information Block
            if (this.use_academic_trad_tables && this.credentials_academic_trad_tables != null) {
                //Using data resolver "method 2", see the class for the heuristic                        
                //DataResearcherAugmentedInformation.resolveLocationOfEntities(xml_doc_results, 
                //new LocationDataResolver_Method2(true, this.credentials_academic_trad_tables));                       

                H2DBPool dbpool_academic_trad_tables = new H2DBPool(credentials_academic_trad_tables);
                try {
                    DataResearcherAugmentedInformation.resolveAcademicPosistion(xml_doc_results,
                            dbpool_academic_trad_tables);
                } catch (Exception ex) {
                    Logger.getRootLogger().error("Error academic positions. " + ex.toString());
                }
            }
        } catch (Exception ex) {
            ProjectLogger.LOGGER.error(ex.getMessage());
        } finally {
            if (this.occursUncaugthExceptionInGateProcess) {
                if (parser != null) {
                    ProjectLogger.LOGGER.info("Begin reload GATE parser because succeded a uncaughtException!");
                    try {
                        parser.endActions();
                        parser.iniActions();
                    } catch (Exception ex) {
                        ProjectLogger.LOGGER.error(null, ex);
                    }
                    ProjectLogger.LOGGER.info("Done!");
                }
            }

            if (parserRepPrePro != null)
                parserRepPrePro.clearData();

            if (repXML != null)
                repXML.clearData();
        }
    } else {
        ProjectLogger.LOGGER.info(this.iaux + " can't get GATE Data Extractor resource");
        this.xml_doc_results = null;
    }
}

From source file:com.mirth.connect.donkey.server.channel.DestinationConnector.java

public void stop() throws ConnectorTaskException, InterruptedException {
    updateCurrentState(DeployedState.STOPPING);

    if (MapUtils.isNotEmpty(queueThreads)) {
        try {// w  w  w  . ja  v a 2  s  . c  o  m
            for (Thread thread : queueThreads.values()) {
                thread.join();
            }

            queueThreads.clear();
        } finally {
            // Invalidate the queue's buffer when the queue is stopped to prevent the buffer becoming 
            // unsynchronized with the data store.
            queue.invalidate(false, true);
        }
    }

    try {
        onStop();
        updateCurrentState(DeployedState.STOPPED);
    } catch (Throwable t) {
        Throwable cause = t;

        if (cause instanceof ConnectorTaskException) {
            cause = cause.getCause();
        }
        if (cause instanceof ExecutionException) {
            cause = cause.getCause();
        }
        if (cause instanceof InterruptedException) {
            throw (InterruptedException) cause;
        }

        updateCurrentState(DeployedState.STOPPED);

        if (t instanceof ConnectorTaskException) {
            throw (ConnectorTaskException) t;
        } else {
            throw new ConnectorTaskException(t);
        }
    }
}

From source file:com.ucuenca.pentaho.plugin.step.oai.OAILoaderDialog.java

public String open() {

    // store some convenient SWT variables
    Shell parent = getParent();//from   w  w  w  .j  a  v  a 2  s .co m
    Display display = parent.getDisplay();

    // SWT code for preparing the dialog
    shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX);
    props.setLook(shell);
    setShellImage(shell, meta);

    // place for modifyListener

    ModifyListener lsMod = new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            meta.setChanged();

            if (!valueUri.equals(txtURI.getText())) {
                prefix = null;
                xpath = null;
                Xpath.setEnabled(false);
                cbmPrefix.setEnabled(false);
            }

        }
    };
    //changed = meta.hasChanged();

    // ------------------------------------------------------- //
    // SWT code for building the actual settings dialog //
    // ------------------------------------------------------- //
    FormLayout formLayout = new FormLayout();
    formLayout.marginWidth = Const.FORM_MARGIN;
    formLayout.marginHeight = Const.FORM_MARGIN;

    shell.setLayout(formLayout);
    shell.setText(BaseMessages.getString(PKG, "OAILoader.Shell.Title"));

    middle = props.getMiddlePct();
    margin = Const.MARGIN;

    // Stepname line
    wlStepname = new Label(shell, SWT.RIGHT);
    wlStepname.setText(BaseMessages.getString(PKG, "System.Label.StepName"));
    props.setLook(wlStepname);
    fdlStepname = new FormData();
    fdlStepname.left = new FormAttachment(0, 0);
    fdlStepname.top = new FormAttachment(0, margin);
    fdlStepname.right = new FormAttachment(middle, -margin);
    wlStepname.setLayoutData(fdlStepname);

    wStepname = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
    wStepname.setText(stepname);
    props.setLook(wStepname);
    wStepname.addModifyListener(lsMod);
    fdStepname = new FormData();
    fdStepname.left = new FormAttachment(middle, 0);
    fdStepname.top = new FormAttachment(0, margin);
    fdStepname.right = new FormAttachment(100, 0);
    wStepname.setLayoutData(fdStepname);

    // add components to grupLayout
    lbURI = new Label(shell, SWT.RIGHT);
    lbURI.setText(BaseMessages.getString(PKG, "OAILoader.FieldName.Label"));
    props.setLook(lbURI);
    fdlbURI = new FormData();
    fdlbURI.left = new FormAttachment(0, 0);
    fdlbURI.right = new FormAttachment(middle, -margin);
    fdlbURI.top = new FormAttachment(wStepname, margin);
    lbURI.setLayoutData(fdlbURI);

    txtURI = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
    txtURI.setText(meta.getInputURI());
    props.setLook(txtURI);
    txtURI.addModifyListener(lsMod);
    fdtxtURI = new FormData();
    fdtxtURI.left = new FormAttachment(middle, 0);
    fdtxtURI.right = new FormAttachment(100, 0);
    fdtxtURI.top = new FormAttachment(wStepname, margin);
    txtURI.setLayoutData(fdtxtURI);

    // button for get all formats of the server OAI-PHM

    lbPrefijo = new Label(shell, SWT.RIGHT);

    lbPrefijo.setText(BaseMessages.getString(PKG, "OAILoader.FieldName.Prefix"));
    props.setLook(lbPrefijo);
    fdlbPrefijo = new FormData();
    fdlbPrefijo.left = new FormAttachment(0, 0);
    fdlbPrefijo.right = new FormAttachment(middle, -margin);
    fdlbPrefijo.top = new FormAttachment(txtURI, margin);
    lbPrefijo.setLayoutData(fdlbPrefijo);

    cbmPrefix = new CCombo(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
    cbmPrefix.setEditable(true);
    props.setLook(cbmPrefix);
    cbmPrefix.addModifyListener(lsMod);
    fbcbmPrefix = new FormData();
    fbcbmPrefix.left = new FormAttachment(middle, 0);
    fbcbmPrefix.top = new FormAttachment(txtURI, margin);
    fbcbmPrefix.height = 23;
    cbmPrefix.setEditable(false);
    cbmPrefix.setEnabled(false);
    cbmPrefix.addSelectionListener(new SelectionListener() {
        public void widgetSelected(SelectionEvent arg0) {
            prefix = cbmPrefix.getText();
            electedItem = cbmPrefix.getSelectionIndex();
            schema = (Schema) schemas.get(cbmPrefix.getSelectionIndex());
            txtXpath.setText("");
            Xpath.setEnabled(true);
        }

        public void widgetDefaultSelected(SelectionEvent arg0) {
        }
    });

    getFormats = new Button(shell, SWT.PUSH | SWT.SINGLE | SWT.MEDIUM | SWT.BORDER);
    props.setLook(getFormats);

    getFormats.setText(BaseMessages.getString(PKG, "OAILoader.InputData.Formats"));
    getFormats.setToolTipText(BaseMessages.getString(PKG, "System.Tooltip.BrowseForFileOrDirAndAdd"));
    fdGetFormats = new FormData();
    fdGetFormats.right = new FormAttachment(100, 0);
    fdGetFormats.top = new FormAttachment(txtURI, margin);
    getFormats.setLayoutData(fdGetFormats);

    fbcbmPrefix.right = new FormAttachment(getFormats, -margin);
    cbmPrefix.setLayoutData(fbcbmPrefix);

    getFormats.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {

            Pattern pat = Pattern.compile("^http://.*");
            Matcher mat = pat.matcher(txtURI.getText());
            if (mat.matches()) { // entonces es una uri
                //meta.setInputURI(txtURI.getText());   
                valueUri = txtURI.getText();
                cbmPrefix.setText("");
                txtXpath.setText("");
                listPrefix(txtURI.getText());
            } else {

                MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                dialog.setText("ERROR");
                dialog.setMessage(BaseMessages.getString(PKG, "OAILoader.Manager.ERRORURI"));

                dialog.open();
                cbmPrefix.setEnabled(false);
                cbmPrefix.setText("");
                txtXpath.setText("");
            }

        }

    });

    Xpath = new Button(shell, SWT.PUSH);
    props.setLook(Xpath);

    Xpath.setText(BaseMessages.getString(PKG, "OAILoader.ButtonName.Title"));
    Xpath.setToolTipText(BaseMessages.getString(PKG, "System.Tooltip.BrowseForFileOrDirAndAdd"));
    fdXpath = new FormData();
    fdXpath.left = new FormAttachment(middle, 0);
    fdXpath.right = new FormAttachment(50, 0);
    fdXpath.top = new FormAttachment(cbmPrefix, margin);
    Xpath.setLayoutData(fdXpath);
    Xpath.setEnabled(false);
    Xpath.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            try {
                getLoopPathList();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (ParserConfigurationException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (SAXException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (TransformerException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    });

    txtXpath = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
    props.setLook(txtXpath);
    txtXpath.addModifyListener(lsMod);
    fdtxtPrefijo = new FormData();
    fdtxtPrefijo.left = new FormAttachment(Xpath, 0);
    fdtxtPrefijo.right = new FormAttachment(100, 0);
    fdtxtPrefijo.top = new FormAttachment(getFormats, margin);
    txtXpath.setLayoutData(fdtxtPrefijo);
    txtXpath.setEditable(false);

    //must be included for DataBase Data Loading
    precatchDataButton = new Button(shell, SWT.PUSH);
    props.setLook(precatchDataButton);
    precatchDataButton.setText(BaseMessages.getString(PKG, "OAILoader.PrecatchButton.Title"));
    precatchDataButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            OAILoaderData data = (OAILoaderData) meta.getStepData();
            setDialogMetadata();
            data.getDataLoader().setStepName(meta.getStepName());

            MessageBox dialog1 = new MessageBox(shell, SWT.ICON_WORKING | SWT.OK);
            dialog1.setText("Dialog");
            dialog1.setMessage(BaseMessages.getString(PKG, "Precatching.StartDialog.Text"));
            dialog1.open();
            data.initOAIHarvester(meta, data, true);
            DBLoader dbloader = new DBLoader(data);
            Thread thread = new Thread(dbloader);
            thread.start();
            try {
                thread.join();
                if (dbloader.status != null) {
                    MessageBox dialog = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                    dialog.setText("Dialog");
                    dialog.setMessage(BaseMessages.getString(PKG, "Precatching.FinishDialog.Text"));
                    dialog.open();
                } else if (dbloader.exception != null) {
                    new ErrorDialog(shell, "Dialog", "Message: ", dbloader.exception);
                }
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
        }
    });

    // OK and cancel buttons
    wOK = new Button(shell, SWT.PUSH);
    wOK.setText(BaseMessages.getString(PKG, "System.Button.OK"));
    wCancel = new Button(shell, SWT.PUSH);
    wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel"));

    //must be included for DataBase Data Loading
    BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wCancel, precatchDataButton }, margin,
            txtXpath);

    // Add listeners for cancel and OK
    lsCancel = new Listener() {
        public void handleEvent(Event e) {
            cancel();
        }
    };
    lsOK = new Listener() {
        public void handleEvent(Event e) {
            ok();
        }
    };

    wCancel.addListener(SWT.Selection, lsCancel);
    wOK.addListener(SWT.Selection, lsOK);

    // default listener (for hitting "enter")
    lsDef = new SelectionAdapter() {
        public void widgetDefaultSelected(SelectionEvent e) {
            ok();
        }
    };
    wStepname.addSelectionListener(lsDef);

    txtURI.addSelectionListener(lsDef);

    // Detect X or ALT-F4 or something that kills this window and cancel the
    // dialog properly
    shell.addShellListener(new ShellAdapter() {
        public void shellClosed(ShellEvent e) {
            cancel();
        }
    });

    // Set/Restore the dialog size based on last position on screen
    // The setSize() method is inherited from BaseStepDialog
    setSize();

    // populate the dialog with the values from the meta object
    populateDialog();

    // restore the changed flag to original value, as the modify listeners
    // fire during dialog population
    meta.setChanged(changed);

    // open dialog and enter event loop
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }

    // at this point the dialog has closed, so either ok() or cancel() have
    // been executed
    // The "stepname" variable is inherited from BaseStepDialog
    return stepname;
}

From source file:com.entertailion.java.caster.RampClient.java

private void getWebSocket(String app) {
    try {//from   ww  w.  j  a  va  2s  . c o m
        int responseCode = 0;
        // Keep trying to get the app status until the
        // connection service URL is available
        state = STATE_STOPPED;
        do {
            responseCode = getAppStatus(defaultHttpClient, dialServer.getAppsUrl() + app);
            if (responseCode != 200) {
                if (responseCode == 404) {
                    Log.e(LOG_TAG, "APP ID is invalid");
                }
                break;
            }
            parseXml(new StringReader(response));
            Log.d(LOG_TAG, "state=" + state);
            Log.d(LOG_TAG, "connectionServiceUrl=" + connectionServiceUrl);
            Log.d(LOG_TAG, "protocol=" + protocol);
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
            }
        } while (state.equals(STATE_RUNNING) && connectionServiceUrl == null);

        if (connectionServiceUrl == null) {
            Log.i(LOG_TAG, "connectionServiceUrl is null");
            return; // oops, something went wrong
        }

        // get the websocket URL
        String webSocketAddress = null;
        HttpPost httpPost = new HttpPost(connectionServiceUrl); // "http://192.168.0.17:8008/connection/YouTube"
        httpPost.setHeader(HEADER_CONNECTION, HEADER_CONNECTION_VALUE);
        httpPost.setHeader(HEADER_ORIGN, HEADER_ORIGIN_VALUE);
        httpPost.setHeader(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE);
        httpPost.setHeader(HEADER_DNT, HEADER_DNT_VALUE);
        httpPost.setHeader(HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_ENCODING_VALUE);
        httpPost.setHeader(HEADER_ACCEPT, HEADER_ACCEPT_VALUE);
        httpPost.setHeader(HEADER_ACCEPT_LANGUAGE, HEADER_ACCEPT_LANGUAGE_VALUE);
        httpPost.setHeader(HEADER_CONTENT_TYPE, HEADER_CONTENT_TYPE_JSON_VALUE);
        httpPost.setEntity(new StringEntity("{\"channel\":0,\"senderId\":{\"appName\":\"" + app
                + "\", \"senderId\":\"" + senderId + "\"}}"));

        HttpResponse httpResponse = defaultHttpClient.execute(httpPost, localContext);
        if (httpResponse != null) {
            responseCode = httpResponse.getStatusLine().getStatusCode();
            Log.d(LOG_TAG, "post response code=" + responseCode);
            if (responseCode == 200) {
                // should return JSON payload
                response = EntityUtils.toString(httpResponse.getEntity());
                Log.d(LOG_TAG, "post response=" + response);
                Header[] headers = httpResponse.getAllHeaders();
                for (int i = 0; i < headers.length; i++) {
                    Log.d(LOG_TAG, headers[i].getName() + "=" + headers[i].getValue());
                }

                // http://code.google.com/p/json-simple/
                JSONParser parser = new JSONParser();
                try {
                    Object obj = parser.parse(new StringReader(response)); // {"URL":"ws://192.168.0.17:8008/session?33","pingInterval":0}
                    JSONObject jsonObject = (JSONObject) obj;
                    webSocketAddress = (String) jsonObject.get("URL");
                    Log.d(LOG_TAG, "webSocketAddress: " + webSocketAddress);
                    long pingInterval = (Long) jsonObject.get("pingInterval"); // TODO
                } catch (Exception e) {
                    Log.e(LOG_TAG, "parse JSON", e);
                }
            }
        } else {
            Log.i(LOG_TAG, "no post response");
            return;
        }

        // Make a web socket connection for doing RAMP
        // to control media playback
        this.started = false;
        this.closed = false;
        this.gotStatus = false;
        if (webSocketAddress != null) {
            // https://github.com/TooTallNate/Java-WebSocket
            URI uri = URI.create(webSocketAddress);

            rampWebSocketClient = new RampWebSocketClient(uri, this);

            new Thread(new Runnable() {
                public void run() {
                    Thread t = new Thread(rampWebSocketClient);
                    t.start();
                    try {
                        t.join();
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    } finally {
                        rampWebSocketClient.close();
                    }
                }
            }).start();
        } else {
            Log.i(LOG_TAG, "webSocketAddress is null");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "getWebSocket", e);
    }
}

From source file:com.thoughtworks.go.server.service.PipelineConfigServicePerformanceTest.java

private void run(Runnable runnable, int numberOfRequests, final ConcurrentHashMap<String, Boolean> results)
        throws InterruptedException {
    Boolean finalResult = true;//from  w  w  w.  j a v a  2s .  c  om
    LOGGER.info("Tests start now!");
    final ArrayList<Thread> threads = new ArrayList<>();
    for (int i = 0; i < numberOfRequests; i++) {
        Thread t = new Thread(runnable, "pipeline" + i);
        threads.add(t);
    }
    for (Thread t : threads) {
        Thread.sleep(1000 * (new Random().nextInt(3) + 1));
        t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread t, Throwable e) {
                LOGGER.error("Exception " + e + " from thread " + t);
                results.put(t.getName(), false);
            }
        });
        t.start();
    }
    for (Thread t : threads) {
        int i = threads.indexOf(t);
        if (i == (numberOfRequests - 1)) {
            //                takeHeapDump(dumpDir, i);
        }
        t.join();
    }
    for (String threadId : results.keySet()) {
        finalResult = results.get(threadId) && finalResult;
    }
    assertThat(finalResult, is(true));
}

From source file:com.cubeia.maven.plugin.firebase.FirebaseRunPlugin.java

protected void doLaunch(FirebaseDirectory dir) throws MojoExecutionException {
    ClassLoader loader = createClassLoader(dir);
    try {//from  w  ww  .  j av a2s . co  m
        Class<?> serverClass = loader.loadClass(SERVER_CLASS);
        String[] cmds = createCommandLine(dir);
        getLog().info("Attempting to start Firebase server.");
        Method method = serverClass.getMethod("main", cmds.getClass());
        method.invoke(null, (Object) cmds);
    } catch (ClassNotFoundException e) {
        throw new MojoExecutionException("Server class '" + SERVER_CLASS + "' not found", e);
    } catch (Exception e) {
        throw new MojoExecutionException("Reflection error", e);
    }
    /*
     * Major hack here, we'll find the server main thread and wait for it...
     */
    Thread th = findServerMainThread();
    if (th == null)
        throw new MojoExecutionException(
                "Firebase Server sub-process did not start correctly; Please check the logs ("
                        + new File(dir.firebaseDirectory, "logs/") + ").");
    else {
        try {
            th.join();
        } catch (InterruptedException e) {
        }
    }
}

From source file:edu.uga.cs.fluxbuster.clustering.ClusterGenerator.java

/**
 * Compute a distance matrix from a list of candidate flux domains with
 * a maximum number of calculation threads.
 *
 * @param cfds the list of candidate flux domains
 * @param maxnumthreads the thread ceiling
 * @return the vector of values in the distance matrix in row major
 *       order//  w w w.  ja v a2 s . co  m
 */
private Vector<Float> computeDistanceMatrixMultiThreaded(List<CandidateFluxDomain> cfds, int maxnumthreads) {
    Vector<Float> retval = new Vector<Float>();
    ThreadFactory tf = Executors.defaultThreadFactory();
    double gamma = Double.parseDouble(localprops.getProperty(GAMMAKEY));
    ArrayList<Thread> threads = new ArrayList<Thread>();
    ArrayList<HashSet<Integer>> threadrows = new ArrayList<HashSet<Integer>>();

    int interval = (int) Math.ceil((cfds.size() - 1) / (double) maxnumthreads);
    int left = 0;
    int right = cfds.size() - 2;
    HashSet<Integer> curset = null;
    boolean addLeftFirst = true;

    while (left <= right) {
        if (curset == null) {
            curset = new HashSet<Integer>();
        }

        if (curset.size() == interval) {
            threadrows.add(curset);
            curset = null;
        } else {
            if (addLeftFirst) {
                curset.add(left++);
            } else {
                curset.add(right--);
            }
            addLeftFirst = !addLeftFirst;

            if (curset.size() == interval) {
                continue;
            }

            if (addLeftFirst) {
                curset.add(left++);
            } else {
                curset.add(right--);
            }
        }
    }
    if (curset != null && curset.size() > 0) {
        threadrows.add(curset);
    }

    ArrayList<Vector<Float>> resultsList = new ArrayList<Vector<Float>>(cfds.size());
    // this is necessary to make sure that the proper indexes exist in
    // resultsList before being accessed by the threads
    for (int i = 0; i < cfds.size() - 1; i++) {
        resultsList.add(null);
    }

    for (int i = 0; i < threadrows.size(); i++) {
        Thread t = tf.newThread(new DistanceMatrixCalculator(gamma, threadrows.get(i), cfds, resultsList));
        threads.add(t);
    }

    for (Thread t : threads) {
        t.start();
    }

    for (Thread t : threads) {
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    for (int i = 0; i < resultsList.size(); i++) {
        retval.addAll(resultsList.get(i));
    }

    return retval;
}

From source file:com.dataartisans.queryablestatedemo.BumpEventGeneratorSource.java

@Override
public void run(SourceContext<BumpEvent> sourceContext) throws Exception {
    final Random rand = new Random();
    final AtomicLong count = new AtomicLong();

    Thread throughputLogger = null;
    if (printThroughput) {
        throughputLogger = new Thread(new ThroughputLogger(count), "ThroughputLogger");
        throughputLogger.start();/*from  w ww .ja v a 2 s .co  m*/
    }

    try {
        while (running) {
            // Generate random events
            final int userId = rand.nextInt(Integer.MAX_VALUE);

            final String itemCase = RandomStringUtils.randomAlphanumeric(ITEM_ID_NUM_CHARS).toLowerCase();

            synchronized (sourceContext.getCheckpointLock()) {
                sourceContext.collect(new BumpEvent(userId, itemCase));
            }

            // Increment count for throughput logger
            count.incrementAndGet();

            Thread.yield();
        }
    } finally {
        if (throughputLogger != null) {
            throughputLogger.interrupt();
            throughputLogger.join();
        }
    }
}