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:com.thoughtworks.go.server.service.BackupServiceIntegrationTest.java

@Test
public void shouldReturnBackupStartedBy() throws InterruptedException {
    assertThat(backupService.backupStartedBy(), is(Optional.empty()));

    final Semaphore waitForBackupToStart = new Semaphore(1);
    final Semaphore waitForAssertionToCompleteWhileBackupIsOn = new Semaphore(1);
    final BackupUpdateListener backupUpdateListener = new BackupUpdateListener() {
        private boolean backupStarted = false;

        @Override/*from ww w  .  j  av  a2s .  c o m*/
        public void updateStep(BackupProgressStatus step) {
            if (!backupStarted) {
                backupStarted = true;
                waitForBackupToStart.release();
                try {
                    waitForAssertionToCompleteWhileBackupIsOn.acquire();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        @Override
        public void error(String message) {
        }

        @Override
        public void completed() {
        }
    };

    waitForAssertionToCompleteWhileBackupIsOn.acquire();
    waitForBackupToStart.acquire();
    Thread backupThd = new Thread(() -> backupService.startBackup(admin, backupUpdateListener));

    backupThd.start();
    waitForBackupToStart.acquire();
    String backupStartedBy = backupService.backupStartedBy().get();
    ServerBackup runningBackup = (ServerBackup) ReflectionUtil.getField(backupService, "runningBackup");

    assertThat(runningBackup.getUsername(), is(backupStartedBy));
    waitForAssertionToCompleteWhileBackupIsOn.release();
    backupThd.join();
}

From source file:com.ucuenca.pentaho.plugin.step.owl.GetPropertiesOWLDialog.java

/**
 * This method is called by Spoon when the user opens the settings dialog of
 * the step. It should open the dialog and return only once the dialog has
 * been closed by the user.//  w  w w .jav a2s.  com
 * 
 * If the user confirms the dialog, the meta object (passed in the
 * constructor) must be updated to reflect the new step settings. The
 * changed flag of the meta object must reflect whether the step
 * configuration was changed by the dialog.
 * 
 * If the user cancels the dialog, the meta object must not be updated, and
 * its changed flag must remain unaltered.
 * 
 * The open() method must return the name of the step after the user has
 * confirmed the dialog, or null if the user cancelled the dialog.
 */
public String open() {

    // store some convenient SWT variables
    Shell parent = getParent();
    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);

    // Save the value of the changed flag on the meta object. If the user
    // cancels
    // the dialog, it will be restored to this saved value.
    // The "changed" variable is inherited from BaseStepDialog
    changed = meta.hasChanged();

    // The ModifyListener used on all controls. It will update the meta
    // object to
    // indicate that changes are being made.
    ModifyListener lsMod = new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            meta.setChanged();
        }
    };

    // ------------------------------------------------------- //
    // 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, "GetPropertiesOWL.Shell.Title"));

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

    // Stepname line

    //---------------------

    // Stepname line
    wlStepname = new Label(shell, SWT.RIGHT);
    wlStepname.setText(BaseMessages.getString(PKG, "System.Label.StepNameLabel"));
    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(BaseMessages.getString(PKG, "System.Label.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);
    //------------------

    // output field value
    Label wlValName = new Label(shell, SWT.RIGHT);
    wlValName.setText(BaseMessages.getString(PKG, "GetPropertiesOWL.FieldName.Label"));
    props.setLook(wlValName);
    FormData fdlValName = new FormData();
    fdlValName.left = new FormAttachment(0, 0);
    fdlValName.right = new FormAttachment(middle, -margin);
    fdlValName.top = new FormAttachment(wStepname, margin);
    //fdlValName.top = new FormAttachment(10, margin);

    wlValName.setLayoutData(fdlValName);

    wHelloFieldName = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
    props.setLook(wHelloFieldName);
    wHelloFieldName.addModifyListener(lsMod);
    FormData fdValName = new FormData();
    fdValName.left = new FormAttachment(middle, 0);
    fdValName.right = new FormAttachment(100, 0);
    fdValName.top = new FormAttachment(wlStepname, margin + 10);
    wHelloFieldName.setLayoutData(fdValName);

    //------------

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

            MessageBox dialog1 = new MessageBox(shell, SWT.ICON_WORKING | SWT.OK);
            dialog1.setText("Dialog");
            dialog1.setMessage(BaseMessages.getString(PKG, "Precatching.StartDialog.Text"));
            dialog1.open();
            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"));
    wLoadFile = new Button(shell, SWT.PUSH);
    wLoadFile.setText(BaseMessages.getString(PKG, "GetPropertiesOWL.FieldName.LoadFile"));
    wAddUri = new Button(shell, SWT.PUSH);
    wAddUri.setText(BaseMessages.getString(PKG, "GetPropertiesOWL.FieldName.AddUri"));
    wbEraseRecord = new Button(shell, SWT.PUSH);

    wbEraseRecord.setText(BaseMessages.getString(PKG, "GetPropertiesOWL.FieldName.delete"));
    // BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK,
    // wCancel, wLoadFile }, margin, wHelloFieldName);
    BaseStepDialog.positionBottomButtons(shell, new Button[] { this.wAddUri, wLoadFile, wbEraseRecord }, margin,
            wHelloFieldName);

    // tabla
    table = new Table(shell, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);
    table.setLinesVisible(true);
    table.setHeaderVisible(true);

    String[] titles = { BaseMessages.getString(PKG, "GetPropertiesOWL.FieldName.col1"),
            BaseMessages.getString(PKG, "GetPropertiesOWL.FieldName.col2"),
            BaseMessages.getString(PKG, "GetPropertiesOWL.FieldName.col3"),
            BaseMessages.getString(PKG, "GetPropertiesOWL.FieldName.col4") };
    for (int i = 0; i < titles.length; i++) {
        TableColumn column = new TableColumn(table, SWT.NONE);
        column.setText(titles[i]);
        column.setWidth(400);
        if (i == 0) {
            column.setWidth(100);
        }

    }
    /**
          for (int i = 0; i < titles.length; i++) {
             table.getColumn(i).pack();
          }*/
    table.setSize(table.computeSize(SWT.DEFAULT, 200));
    table.setItemCount(6);// para ver las filas por defecto
    // parametrizando el forma data
    fdmitabla = new FormData();
    // fdmitabla.left = new FormAttachment(middle, 0);
    fdmitabla.left = new FormAttachment(1, 0);
    fdmitabla.right = new FormAttachment(100, 1);
    fdmitabla.top = new FormAttachment(wLoadFile, margin);

    // boton ok y cancel al ultimo

    table.setLayoutData(fdmitabla);

    BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wCancel, precatchDataButton }, margin,
            table);
    /**
     * fdok = new FormData(); fdok.left = new FormAttachment(wCancel,
     * middle); //fdok.right = new FormAttachment(100, 0);
     * 
     * fdok.top = new FormAttachment(table, margin);
     * wOK.setLayoutData(this.fdok); fdcancel = new FormData(); // fdok.left
     * = new FormAttachment(wCancel, middle); fdcancel.right = new
     * FormAttachment(wCancel,middle); fdcancel.top = new
     * FormAttachment(table, margin); wCancel.setLayoutData(this.fdcancel);
     */

    // Add listeners for cancel and OK

    lsCancel = new Listener() {
        public void handleEvent(Event e) {
            cancel();
        }
    };
    lsOK = new Listener() {
        public void handleEvent(Event e) {
            ok();
        }
    };
    lsLoadFile = new Listener() {
        public void handleEvent(Event e) {
            LoadFile();
        }
    };
    lsReadUri = new Listener() {
        public void handleEvent(Event e) {
            AddUri();
        }
    };
    lsTable = new Listener() {
        public void handleEvent(Event e) {
            GetSelectedRow();
        }
    };
    lsBottonErase = new Listener() {
        public void handleEvent(Event e) {
            BorrarFila();
        }
    };

    wCancel.addListener(SWT.Selection, lsCancel);
    wOK.addListener(SWT.Selection, lsOK);
    wLoadFile.addListener(SWT.Selection, lsLoadFile);
    this.wAddUri.addListener(SWT.Selection, lsReadUri);
    this.table.addListener(SWT.Selection, lsTable);
    this.wbEraseRecord.addListener(SWT.Selection, this.lsBottonErase);
    // default listener (for hitting "enter")
    lsDef = new SelectionAdapter() {
        public void widgetDefaultSelected(SelectionEvent e) {
            ok();
        }
    };
    // wStepname.addSelectionListener(lsDef);
    wHelloFieldName.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:edu.unc.lib.deposit.fcrepo3.IngestDepositTest.java

@Test
public void testRunFailObjectIngest() throws Exception {

    when(client.ingestRaw(any(byte[].class), any(Format.class), anyString())).thenReturn(new PID("pid"))
            .thenReturn(new PID("pid")).thenThrow(new FedoraException(""));

    Thread jobThread = new Thread(job);
    final boolean[] exceptionCaught = new boolean[] { false };
    Thread.UncaughtExceptionHandler jobFailedHandler = new Thread.UncaughtExceptionHandler() {
        @Override/* w  w  w .j a v  a2  s.  c o  m*/
        public void uncaughtException(Thread th, Throwable ex) {
            if (ex instanceof JobFailedException)
                exceptionCaught[0] = true;
        }
    };

    jobThread.setUncaughtExceptionHandler(jobFailedHandler);
    jobThread.start();

    // Start processing with a timelimit to prevent infinite wait in case of failure
    jobThread.join();

    // Only the one successful top level pid added because of ordering
    verify(client).addObjectRelationship(any(PID.class), anyString(), any(PID.class));

    // Failing on third ingestRaw
    verify(client, times(3)).ingestRaw(any(byte[].class), any(Format.class), anyString());

    // Only one object with data should have been uploaded
    verify(client).upload(any(File.class));

    // PREMIS was written
    verify(client, times(0)).writePremisEventsToFedoraObject(any(PremisEventLogger.class), any(PID.class));

    assertTrue("Job must have been registered", jmsListener.registeredJob);
    assertTrue("Job must have been unregistered on failure", jmsListener.registeredJob);

    assertTrue("Exception must have been thrown by job", exceptionCaught[0]);

}

From source file:com.meltmedia.dropwizard.etcd.json.EtcdWatchServiceIT.java

@Test
public void shouldWatchMultipleDirectories() throws InterruptedException {
    int dir1Count = 1000;
    int dir2Count = 500;
    int dir3Count = 750;

    // add a directory watch.
    WatchService service = serviceRule.getService();

    EtcdDirectoryDao<NodeData> dir1Dao = new EtcdDirectoryDao<NodeData>(clientRule::getClient,
            BASE_PATH + "/dir1", mapper, NODE_DATA_TYPE);
    EtcdDirectoryDao<NodeData> dir2Dao = new EtcdDirectoryDao<NodeData>(clientRule::getClient,
            BASE_PATH + "/dir2", mapper, NODE_DATA_TYPE);
    EtcdDirectoryDao<NodeData> dir3Dao = new EtcdDirectoryDao<NodeData>(clientRule::getClient,
            BASE_PATH + "/dir3", mapper, NODE_DATA_TYPE);

    @SuppressWarnings("unchecked")
    EtcdEventHandler<NodeData> handler1 = mock(EtcdEventHandler.class);
    @SuppressWarnings("unchecked")
    EtcdEventHandler<NodeData> handler2 = mock(EtcdEventHandler.class);

    Thread dir1Events = startNodeDataThread(dir1Dao, dir1Count);
    Thread dir2Events = startNodeDataThread(dir2Dao, dir2Count);
    Thread dir3Events = startNodeDataThread(dir3Dao, dir3Count);

    try {/*from  ww  w .  j  a  va2 s  .c  o m*/
        service.registerDirectoryWatch("/dir1", new TypeReference<NodeData>() {
        }, handler1);
        Thread.sleep(10);
        service.registerDirectoryWatch("/dir2", new TypeReference<NodeData>() {
        }, handler2);

        verifySequentialNodeData(handler1, dir1Count);
        verifySequentialNodeData(handler2, dir2Count);
    } finally {
        dir1Events.join();
        dir2Events.join();
        dir3Events.join();
    }
}

From source file:com.esp8266.mkspiffs.ESP8266FS.java

private int listenOnProcess(String[] arguments) {
    try {// w  ww. jav a  2s  .c  om
        final Process p = ProcessUtils.exec(arguments);
        Thread thread = new Thread() {
            public void run() {
                try {
                    InputStreamReader reader = new InputStreamReader(p.getInputStream());
                    int c;
                    while ((c = reader.read()) != -1)
                        System.out.print((char) c);
                    reader.close();

                    reader = new InputStreamReader(p.getErrorStream());
                    while ((c = reader.read()) != -1)
                        System.err.print((char) c);
                    reader.close();
                } catch (Exception e) {
                }
            }
        };
        thread.start();
        int res = p.waitFor();
        thread.join();
        return res;
    } catch (Exception e) {
        return -1;
    }
}

From source file:com.emc.ecs.sync.storage.CasStorageTest.java

@Test
public void testCasSingleObject() throws Exception {
    FPPool sourcePool = new FPPool(connectString1);
    FPPool targetPool = new FPPool(connectString2);

    try {/*from   w  ww  .ja v a  2s .co m*/
        // create clip in source (<=1MB blob size) - capture summary for comparison
        StringWriter sourceSummary = new StringWriter();
        List<String> clipIds = createTestClips(sourcePool, 1048576, 1, sourceSummary);
        String clipID = clipIds.iterator().next();

        // open clip in source
        FPClip clip = new FPClip(sourcePool, clipID, FPLibraryConstants.FP_OPEN_FLAT);

        // buffer CDF
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        clip.RawRead(baos);

        // write CDF to target
        FPClip targetClip = new FPClip(targetPool, clipID, new ByteArrayInputStream(baos.toByteArray()),
                CLIP_OPTIONS);

        // migrate blobs
        FPTag tag, targetTag;
        int tagCount = 0;
        while ((tag = clip.FetchNext()) != null) {
            targetTag = targetClip.FetchNext();
            Assert.assertEquals("Tag names don't match", tag.getTagName(), targetTag.getTagName());
            Assert.assertTrue("Tag " + tag.getTagName() + " attributes not equal",
                    Arrays.equals(tag.getAttributes(), targetTag.getAttributes()));

            int blobStatus = tag.BlobExists();
            if (blobStatus == 1) {
                PipedInputStream pin = new PipedInputStream(BUFFER_SIZE);
                PipedOutputStream pout = new PipedOutputStream(pin);
                BlobReader reader = new BlobReader(tag, pout);

                // start reading in parallel
                Thread readThread = new Thread(reader);
                readThread.start();

                // write inside this thread
                targetTag.BlobWrite(pin);

                readThread.join(); // this shouldn't do anything, but just in case

                if (!reader.isSuccess())
                    throw new Exception("blob read failed", reader.getError());
            } else {
                if (blobStatus != -1)
                    System.out.println("blob unavailable, clipId=" + clipID + ", tagNum=" + tagCount
                            + ", blobStatus=" + blobStatus);
            }
            tag.Close();
            targetTag.Close();
            tagCount++;
        }

        clip.Close();

        Assert.assertEquals("clip IDs not equal", clipID, targetClip.Write());
        targetClip.Close();

        // check target blob data
        targetClip = new FPClip(targetPool, clipID, FPLibraryConstants.FP_OPEN_FLAT);
        Assert.assertEquals("content mismatch", sourceSummary.toString(), summarizeClip(targetClip));
        targetClip.Close();

        // delete in source and target
        FPClip.Delete(sourcePool, clipID);
        FPClip.Delete(targetPool, clipID);
    } finally {
        try {
            sourcePool.Close();
        } catch (Throwable t) {
            log.warn("failed to close source pool", t);
        }
        try {
            targetPool.Close();
        } catch (Throwable t) {
            log.warn("failed to close dest pool", t);
        }
    }
}

From source file:org.apache.camel.component.mongodb.MongoDbTailableCursorConsumerTest.java

@Test
public void testPersistentTailTrackIncreasingDateField() throws Exception {
    assertEquals(0, cappedTestCollection.count());
    final MockEndpoint mock = getMockEndpoint("mock:test");
    final Calendar startTimestamp = Calendar.getInstance();

    // get default tracking collection
    DBCollection trackingCol = db.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION);
    trackingCol.drop();/*from w w w  . jav a  2 s.  co  m*/
    trackingCol = db.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION);

    // create a capped collection with max = 1000
    cappedTestCollection = db.createCollection(cappedTestCollectionName,
            BasicDBObjectBuilder.start().add("capped", true).add("size", 1000000000).add("max", 1000).get());

    addTestRoutes();
    context.startRoute("tailableCursorConsumer2");

    mock.expectedMessageCount(300);
    // pump 300 records
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 1; i <= 300; i++) {
                Calendar c = (Calendar) (startTimestamp.clone());
                c.add(Calendar.MINUTE, i);
                cappedTestCollection.insert(
                        BasicDBObjectBuilder.start("increasing", c.getTime()).add("string", "value" + i).get(),
                        WriteConcern.SAFE);
            }
        }
    });

    // start the data pumping
    t.start();
    // before we continue wait for the data pump to end
    t.join();
    mock.assertIsSatisfied();
    mock.reset();
    // ensure that the persisted lastVal is startTimestamp + 300min
    Calendar cal300 = (Calendar) startTimestamp.clone();
    cal300.add(Calendar.MINUTE, 300);
    context.stopRoute("tailableCursorConsumer2");
    assertEquals(cal300.getTime(), trackingCol.findOne(new BasicDBObject("persistentId", "darwin"))
            .get(MongoDbTailTrackingConfig.DEFAULT_FIELD));
    context.startRoute("tailableCursorConsumer2");

    // expect 300 messages and not 600
    mock.expectedMessageCount(300);
    // pump 300 records
    t = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 301; i <= 600; i++) {
                Calendar c = (Calendar) (startTimestamp.clone());
                c.add(Calendar.MINUTE, i);
                cappedTestCollection.insert(
                        BasicDBObjectBuilder.start("increasing", c.getTime()).add("string", "value" + i).get(),
                        WriteConcern.SAFE);
            }
        }
    });
    // start the data pumping
    t.start();
    // before we continue wait for the data pump to end
    t.join();
    mock.assertIsSatisfied();
    Object firstBody = mock.getExchanges().get(0).getIn().getBody();
    assertTrue(firstBody instanceof DBObject);
    Calendar cal301 = (Calendar) startTimestamp.clone();
    cal301.add(Calendar.MINUTE, 301);
    assertEquals(cal301.getTime(), ((DBObject) firstBody).get("increasing"));
    // check that the persisted lastVal after stopping the route is startTimestamp + 600min
    context.stopRoute("tailableCursorConsumer2");
    Calendar cal600 = (Calendar) startTimestamp.clone();
    cal600.add(Calendar.MINUTE, 600);
    assertEquals(cal600.getTime(), trackingCol.findOne(new BasicDBObject("persistentId", "darwin"))
            .get(MongoDbTailTrackingConfig.DEFAULT_FIELD));
}

From source file:juicebox.data.MatrixZoomData.java

/**
 * Return the blocks of normalized, observed values overlapping the rectangular region specified.
 * The units are "bins"/*from w w  w .  j  a  va2s. co m*/
 *
 * @param binY1 leftmost position in "bins"
 * @param binX2 rightmost position in "bins"
 * @param binY2 bottom position in "bins"
 * @param no    normalization type
 * @return List of overlapping blocks, normalized
 */
public int addNormalizedBlocksToList(final List<Block> blockList, int binX1, int binY1, int binX2, int binY2,
        final NormalizationType no) {

    int col1 = binX1 / blockBinCount;
    int row1 = binY1 / blockBinCount;

    int col2 = binX2 / blockBinCount;
    int row2 = binY2 / blockBinCount;

    List<Integer> blocksToLoad = new ArrayList<Integer>();
    for (int r = row1; r <= row2; r++) {
        for (int c = col1; c <= col2; c++) {
            int blockNumber = r * getBlockColumnCount() + c;

            String key = getKey() + "_" + blockNumber + "_" + no;
            Block b;
            if (HiCGlobals.useCache && blockCache.containsKey(key)) {
                b = blockCache.get(key);
                blockList.add(b);
            } else {
                blocksToLoad.add(blockNumber);
            }
        }
    }

    final AtomicInteger errorCounter = new AtomicInteger();

    List<Thread> threads = new ArrayList<Thread>();
    for (final int blockNumber : blocksToLoad) {
        Runnable loader = new Runnable() {
            @Override
            public void run() {
                try {
                    String key = getKey() + "_" + blockNumber + "_" + no;
                    Block b = reader.readNormalizedBlock(blockNumber, MatrixZoomData.this, no);
                    if (b == null) {
                        b = new Block(blockNumber); // An empty block
                    }
                    if (HiCGlobals.useCache) {
                        blockCache.put(key, b);
                    }
                    blockList.add(b);
                } catch (IOException e) {
                    errorCounter.incrementAndGet();
                }
            }
        };

        Thread t = new Thread(loader);
        threads.add(t);
        t.start();
    }

    // Wait for all threads to complete
    for (Thread t : threads) {
        try {
            t.join();
        } catch (InterruptedException ignore) {
        }
    }

    // untested since files got fixed - MSS
    return errorCounter.get();
}

From source file:com.norconex.collector.http.crawler.ExecutionTest.java

private void testAfterStopped(boolean resume) throws IOException, XMLStreamException, InterruptedException {
    vars.setInt("delay", 5000);

    Thread newCrawl = new Thread() {
        @Override//from  w  w w.j  av  a  2 s.  co m
        public void run() {
            try {
                System.out.println("Starting collector.");
                int returnValue = runCollector("start", vars);
                Assert.assertEquals("Wrong first return value.", 0, returnValue);
            } catch (IOException | XMLStreamException e) {
                throw new RuntimeException(e);
            }
        }
    };
    newCrawl.start();
    Sleeper.sleepSeconds(10);

    System.out.println("Requesting collector to stop.");
    int returnValue = runCollector("stop", null);
    Assert.assertEquals("Wrong stop return value.", 0, returnValue);

    newCrawl.join();

    int fileCount = countAddedFiles();
    Assert.assertTrue("Should not have had time to process more than " + "2 or 3 files",
            fileCount > 1 && fileCount < 4);

    ageProgress(progressDir);
    vars.setInt("delay", 0);

    //--- Resume after stop ---
    if (resume) {
        int exitValue = runCollector("resume", vars);
        Assert.assertEquals("Wrong exit value.", 0, exitValue);
        Assert.assertEquals("Wrong number of committed files after resume.", 10, countAddedFiles());
        //--- Start after stop ---
    } else {
        FileUtil.delete(committedDir);
        vars.setInt("maxDocuments", 2);
        int exitValue = runCollector("start", vars);
        Assert.assertEquals("Wrong exit value.", 0, exitValue);
        Assert.assertEquals("Wrong number of committed files after start.", 2, countAddedFiles());
    }
}

From source file:com.brienwheeler.lib.test.stepper.SteppableThreadTest.java

private void interruptInWait(SteppableThread stepper, TestMode mode) throws InterruptedException {
    final Thread testThread = Thread.currentThread();
    Thread interruptThread = new Thread() {
        @Override/*  w w w  .j  a va 2  s  .  com*/
        public void run() {
            try {
                Thread.sleep(10L);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }

            testThread.interrupt();
        }
    };
    interruptThread.start();

    try {
        if (mode == TestMode.RELEASE)
            stepper.release();
        else if (mode == TestMode.WAITDONE)
            stepper.waitDone();
        else if (mode == TestMode.JOIN)
            stepper.releaseAndJoin();
        Assert.fail();
    } catch (RuntimeException e) {
        Assert.assertTrue(Thread.interrupted()); // test and clear
        Assert.assertEquals(InterruptedException.class, e.getCause().getClass());
    }

    interruptThread.join();
}