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

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

Introduction

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

Prototype

public final native void wait(long timeoutMillis) throws InterruptedException;

Source Link

Document

Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

Usage

From source file:com.alibaba.wasp.client.TestAdmin.java

/**
 * Modify table is async so wait on completion of the table operation in
 * master.// w  w w  .j ava 2  s. co m
 * 
 * @param tableName
 * @param htd
 * @throws java.io.IOException
 */
private void modifyTable(final byte[] tableName, final FTable htd) throws IOException {
    FMasterServices services = TEST_UTIL.getMiniWaspCluster().getMaster();
    ExecutorService executor = services.getExecutorService();
    AtomicBoolean done = new AtomicBoolean(false);
    executor.registerListener(EventType.C_M_MODIFY_TABLE, new DoneListener(done));
    admin.modifyTable(tableName, htd);
    while (!done.get()) {
        synchronized (done) {
            try {
                done.wait(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    executor.unregisterListener(EventType.C_M_MODIFY_TABLE);
}

From source file:com.alibaba.wasp.fserver.handler.OpenEntityGroupHandler.java

/**
 * Update ZK, ROOT or META. This can take a while if for example the .META. is
 * not available -- if server hosting .META. crashed and we are waiting on it
 * to come back -- so run in a thread and keep updating znode state meantime
 * so master doesn't timeout our entityGroup-in-transition. Caller must
 * cleanup entityGroup if this fails.//from w ww  . ja v a 2s  .  c  om
 */
boolean updateMeta(final EntityGroup entityGroup) {
    if (this.server.isStopped() || this.fsServices.isStopping()) {
        return false;
    }
    // Object we do wait/notify on. Make it boolean. If set, we're done.
    // Else, wait.
    final AtomicBoolean signaller = new AtomicBoolean(false);
    PostOpenDeployTasksThread t = new PostOpenDeployTasksThread(entityGroup, this.server, this.fsServices,
            signaller);
    t.start();
    int assignmentTimeout = this.server.getConfiguration()
            .getInt("wasp.master.assignment.timeoutmonitor.period", 10000);
    // Total timeout for meta edit. If we fail adding the edit then close out
    // the entityGroup and let it be assigned elsewhere.
    long timeout = assignmentTimeout * 10;
    long now = System.currentTimeMillis();
    long endTime = now + timeout;
    // Let our period at which we update OPENING state to be be 1/3rd of the
    // entityGroups-in-transition timeout period.
    long period = Math.max(1, assignmentTimeout / 3);
    long lastUpdate = now;
    boolean tickleOpening = true;
    while (!signaller.get() && t.isAlive() && !this.server.isStopped() && !this.fsServices.isStopping()
            && (endTime > now)) {
        long elapsed = now - lastUpdate;
        if (elapsed > period) {
            // Only tickle OPENING if postOpenDeployTasks is taking some time.
            lastUpdate = now;
            tickleOpening = tickleOpening("post_open_deploy");
        }
        synchronized (signaller) {
            try {
                signaller.wait(period);
            } catch (InterruptedException e) {
                // Go to the loop check.
            }
        }
        now = System.currentTimeMillis();
    }
    // Is thread still alive? We may have left above loop because server is
    // stopping or we timed out the edit. Is so, interrupt it.
    if (t.isAlive()) {
        if (!signaller.get()) {
            // Thread still running; interrupt
            LOG.debug("Interrupting thread " + t);
            t.interrupt();
        }
        try {
            t.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted joining " + entityGroup.getEntityGroupInfo().getEntityGroupNameAsString(),
                    ie);
            Thread.currentThread().interrupt();
        }
    }

    // Was there an exception opening the entityGroup? This should trigger on
    // InterruptedException too. If so, we failed. Even if tickle opening fails
    // then it is a failure.
    return ((!Thread.interrupted() && t.getException() == null) && tickleOpening);
}

From source file:org.apache.hadoop.hbase.master.TestZKBasedCloseRegion.java

@Test(timeout = 300000)
public void testCloseRegion() throws Exception {
    LOG.info("Running testCloseRegion");
    MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
    LOG.info("Number of region servers = " + cluster.getLiveRegionServerThreads().size());

    int rsIdx = 0;
    HRegionServer regionServer = TEST_UTIL.getHBaseCluster().getRegionServer(rsIdx);
    Collection<HRegion> regions = regionServer.getOnlineRegions();
    HRegion region = regions.iterator().next();
    LOG.debug("Asking RS to close region " + region.getRegionNameAsString());

    AtomicBoolean closeEventProcessed = new AtomicBoolean(false);
    RegionServerOperationListener listener = new CloseRegionEventListener(region.getRegionNameAsString(),
            closeEventProcessed);//w  w  w .  j av  a 2  s .  co m
    HMaster master = TEST_UTIL.getHBaseCluster().getMaster();
    master.getRegionServerOperationQueue().registerRegionServerOperationListener(listener);
    HMsg closeRegionMsg = new HMsg(HMsg.Type.MSG_REGION_CLOSE, region.getRegionInfo(),
            Bytes.toBytes("Forcing close in test"));
    TEST_UTIL.getHBaseCluster().addMessageToSendRegionServer(rsIdx, closeRegionMsg);

    synchronized (closeEventProcessed) {
        // wait for 3 minutes
        closeEventProcessed.wait(3 * 60 * 1000);
    }
    if (!closeEventProcessed.get()) {
        throw new Exception("Timed out, close event not called on master.");
    } else {
        LOG.info("Done with test, RS informed master successfully.");
    }
}

From source file:org.apache.hadoop.hbase.master.TestZKBasedReopenRegion.java

@Test(timeout = 300000)
public void testOpenRegion() throws Exception {
    MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
    LOG.info("Number of region servers = " + cluster.getLiveRegionServerThreads().size());

    int rsIdx = 0;
    HRegionServer regionServer = TEST_UTIL.getHBaseCluster().getRegionServer(rsIdx);
    Collection<HRegion> regions = regionServer.getOnlineRegions();
    HRegion region = regions.iterator().next();
    LOG.debug("Asking RS to close region " + region.getRegionNameAsString());

    AtomicBoolean closeEventProcessed = new AtomicBoolean(false);
    AtomicBoolean reopenEventProcessed = new AtomicBoolean(false);
    RegionServerOperationListener listener = new ReopenRegionEventListener(region.getRegionNameAsString(),
            closeEventProcessed, reopenEventProcessed);
    HMaster master = TEST_UTIL.getHBaseCluster().getMaster();
    master.getRegionServerOperationQueue().registerRegionServerOperationListener(listener);
    HMsg closeRegionMsg = new HMsg(HMsg.Type.MSG_REGION_CLOSE, region.getRegionInfo(),
            Bytes.toBytes("Forcing close in test"));
    TEST_UTIL.getHBaseCluster().addMessageToSendRegionServer(rsIdx, closeRegionMsg);

    synchronized (closeEventProcessed) {
        closeEventProcessed.wait(3 * 60 * 1000);
    }// w  ww  .j  a  v a 2 s  . c o m
    if (!closeEventProcessed.get()) {
        throw new Exception("Timed out, close event not called on master.");
    }

    synchronized (reopenEventProcessed) {
        reopenEventProcessed.wait(3 * 60 * 1000);
    }
    if (!reopenEventProcessed.get()) {
        throw new Exception("Timed out, open event not called on master after region close.");
    }

    LOG.info("Done with test, RS informed master successfully.");
}

From source file:org.apache.hadoop.hbase.regionserver.handler.OpenRegionHandler.java

/**
 * Update ZK or META.  This can take a while if for example the
 * hbase:meta is not available -- if server hosting hbase:meta crashed and we are
 * waiting on it to come back -- so run in a thread and keep updating znode
 * state meantime so master doesn't timeout our region-in-transition.
 * Caller must cleanup region if this fails.
 */// ww  w  .  ja v  a 2s . co  m
boolean updateMeta(final HRegion r) {
    if (this.server.isStopped() || this.rsServices.isStopping()) {
        return false;
    }
    // Object we do wait/notify on.  Make it boolean.  If set, we're done.
    // Else, wait.
    final AtomicBoolean signaller = new AtomicBoolean(false);
    PostOpenDeployTasksThread t = new PostOpenDeployTasksThread(r, this.server, this.rsServices, signaller);
    t.start();
    // Post open deploy task:
    //   meta => update meta location in ZK
    //   other region => update meta
    // It could fail if ZK/meta is not available and
    // the update runs out of retries.
    long now = System.currentTimeMillis();
    long lastUpdate = now;
    boolean tickleOpening = true;
    while (!signaller.get() && t.isAlive() && !this.server.isStopped() && !this.rsServices.isStopping()
            && isRegionStillOpening()) {
        long elapsed = now - lastUpdate;
        if (elapsed > 120000) { // 2 minutes, no need to tickleOpening too often
            // Only tickle OPENING if postOpenDeployTasks is taking some time.
            lastUpdate = now;
            tickleOpening = tickleOpening("post_open_deploy");
        }
        synchronized (signaller) {
            try {
                // Wait for 10 seconds, so that server shutdown
                // won't take too long if this thread happens to run.
                signaller.wait(10000);
            } catch (InterruptedException e) {
                // Go to the loop check.
            }
        }
        now = System.currentTimeMillis();
    }
    // Is thread still alive?  We may have left above loop because server is
    // stopping or we timed out the edit.  Is so, interrupt it.
    if (t.isAlive()) {
        if (!signaller.get()) {
            // Thread still running; interrupt
            LOG.debug("Interrupting thread " + t);
            t.interrupt();
        }
        try {
            t.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted joining " + r.getRegionInfo().getRegionNameAsString(), ie);
            Thread.currentThread().interrupt();
        }
    }

    // Was there an exception opening the region?  This should trigger on
    // InterruptedException too.  If so, we failed.  Even if tickle opening fails
    // then it is a failure.
    return ((!Thread.interrupted() && t.getException() == null) && tickleOpening);
}

From source file:org.polymap.core.runtime.UIJob.java

/**
 * Waits until this job is finished. This method will block the calling thread
 * until the job has finished executing, or until this thread has been
 * interrupted, or the timeout exceeds. A job must not be joined from within the
 * scope of its run method.// w  ww .  j a v  a 2 s  .c om
 * <p/>
 * This method must be called from the UIThread. It calls readAndDispatch() of
 * the current display, so that the UI is responsive during the call is blocked.
 * 
 * @param timeoutMillis
 * @return False if the job did not finish within the given timeout or the
 *         calling thread was interrupted.
 */
public boolean joinAndDispatch(long timeoutMillis) {

    final AtomicBoolean done = new AtomicBoolean(getState() == Job.NONE);

    IJobChangeListener jobListener = new JobChangeAdapter() {
        public void done(IJobChangeEvent event) {
            synchronized (done) {
                done.set(true);
                done.notify();
            }
        }
    };
    addJobChangeListener(jobListener);

    // check if job is done already - after the listener has been
    // registered; this avoids race cond. between the two
    if (getState() == Job.NONE) {
        removeJobChangeListener(jobListener);
        return true;
    }

    final Display threadDisplay = Display.getCurrent();
    final Timer timer = new Timer();
    while (!done.get() && timer.elapsedTime() < timeoutMillis
            && (threadDisplay == null || !threadDisplay.isDisposed())) {

        Thread.yield();
        if (threadDisplay != null) {
            if (!threadDisplay.readAndDispatch()) {
                synchronized (done) {
                    try {
                        done.wait(300);
                        log.debug("wake after: " + timer.elapsedTime() + "ms");
                    } catch (InterruptedException e) {
                    }
                }
                //                    // just wait on #done blocks hangs;
                //                    // display.sleep() might wait forever, so we need this watchdog
                //                    Polymap.executorService().execute( new Runnable() {
                //                        public void run() {
                //                            synchronized (done) {
                //                                try { done.wait( 300 ); } catch (InterruptedException e) {}
                //                            }
                //                            log.info( "wake ..." );
                //                            threadDisplay.wake();
                //                        }
                //                    });
                //                    threadDisplay.sleep();
            }
        } else {
            synchronized (done) {
                try {
                    done.wait(250);
                } catch (InterruptedException e) {
                }
            }
        }
    }
    removeJobChangeListener(jobListener);
    return done.get();
}