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

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

Introduction

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

Prototype

public final void set(boolean newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:android.support.v7.widget.BaseRecyclerViewInstrumentationTest.java

void smoothScrollToPosition(final int position, boolean assertArrival) throws Throwable {
    if (mDebug) {
        Log.d(TAG, "SMOOTH scrolling to " + position);
    }//ww w .j a  v  a  2  s .  c  o m
    final CountDownLatch viewAdded = new CountDownLatch(1);
    final RecyclerView.OnChildAttachStateChangeListener listener = new RecyclerView.OnChildAttachStateChangeListener() {
        @Override
        public void onChildViewAttachedToWindow(View view) {
            if (position == mRecyclerView.getChildAdapterPosition(view)) {
                viewAdded.countDown();
            }
        }

        @Override
        public void onChildViewDetachedFromWindow(View view) {
        }
    };
    final AtomicBoolean addedListener = new AtomicBoolean(false);
    runTestOnUiThread(new Runnable() {
        @Override
        public void run() {
            RecyclerView.ViewHolder viewHolderForAdapterPosition = mRecyclerView
                    .findViewHolderForAdapterPosition(position);
            if (viewHolderForAdapterPosition != null) {
                viewAdded.countDown();
            } else {
                mRecyclerView.addOnChildAttachStateChangeListener(listener);
                addedListener.set(true);
            }

        }
    });
    runTestOnUiThread(new Runnable() {
        @Override
        public void run() {
            mRecyclerView.smoothScrollToPosition(position);
        }
    });
    getInstrumentation().waitForIdleSync();
    assertThat("should be able to scroll in 10 seconds",
            !assertArrival || viewAdded.await(10, TimeUnit.SECONDS), CoreMatchers.is(true));
    waitForIdleScroll(mRecyclerView);
    if (mDebug) {
        Log.d(TAG, "SMOOTH scrolling done");
    }
    if (addedListener.get()) {
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                mRecyclerView.removeOnChildAttachStateChangeListener(listener);
            }
        });
    }
    getInstrumentation().waitForIdleSync();
}

From source file:com.vmware.admiral.compute.container.HostContainerListDataCollection.java

private void checkIfSystemContainerStateExistsBeforeStartIt(ContainerState containerState,
        ContainerDescription containerDesc, String containerHostLink) {

    QueryTask containerQuery = QueryUtil.buildPropertyQuery(ContainerState.class,
            ContainerState.FIELD_NAME_DESCRIPTION_LINK,
            SystemContainerDescriptions.AGENT_CONTAINER_DESCRIPTION_LINK, ContainerState.FIELD_NAME_PARENT_LINK,
            containerState.parentLink);// w  w  w  .ja v  a  2s. c o m

    QueryUtil.addExpandOption(containerQuery);
    AtomicBoolean stateExists = new AtomicBoolean(false);
    new ServiceDocumentQuery<ContainerState>(getHost(), ContainerState.class).query(containerQuery, (r) -> {
        if (r.hasException()) {
            logWarning("Failed to retrieve system container state: %s", containerState.documentSelfLink);
        } else if (r.hasResult()) {
            // If System ContainerState exists, all supported container
            // operations start/stop will work.
            stateExists.set(true);
        } else {
            if (stateExists.get()) {
                // If System ContainerState exists we can start it.
                // if version is valid, although we don't know the power state,
                // start the containers anyway as start is idempotent
                logFine("start existing system container %s", containerState.documentSelfLink);
                startSystemContainer(containerState, null);
            } else {
                // If System ContainerState does not exists, we create it before
                // start operation.
                final ContainerState systemContainerState = createSystemContainerState(containerState,
                        containerDesc, containerHostLink);

                sendRequest(OperationUtil.createForcedPost(this, ContainerFactoryService.SELF_LINK)
                        .setBody(systemContainerState).setCompletion((o, e) -> {
                            if (e != null) {
                                logWarning("Failure creating system container: " + Utils.toString(e));
                                return;
                            }
                            ContainerState body = o.getBody(ContainerState.class);
                            logInfo("Created system ContainerState: %s ", body.documentSelfLink);
                            createSystemContainerInstanceRequest(body, null);
                            updateNumberOfContainers(containerHostLink);
                            startSystemContainer(containerState, null);
                        }));

            }
        }
    });
}

From source file:com.impetus.client.kudu.schemamanager.KuduDBSchemaManager.java

@Override
protected void update(List<TableInfo> tableInfos) {
    for (TableInfo tableInfo : tableInfos) {
        try {//from w  w w  . j a v a 2s . c  o  m
            if (!client.tableExists(tableInfo.getTableName())) {
                createKuduTable(tableInfo);
            } else {
                List<String> entityColumns = new ArrayList<String>();
                KuduTable table = client.openTable(tableInfo.getTableName());
                AlterTableOptions alterTableOptions = new AlterTableOptions();
                AtomicBoolean updated = new AtomicBoolean(false);
                Schema schema = table.getSchema();
                // add modify columns
                for (ColumnInfo columnInfo : tableInfo.getColumnMetadatas()) {
                    entityColumns.add(columnInfo.getColumnName());
                    alterColumn(alterTableOptions, schema, columnInfo, updated);
                }
                // update for embeddables logic
                for (EmbeddedColumnInfo embColumnInfo : tableInfo.getEmbeddedColumnMetadatas()) {
                    for (ColumnInfo columnInfo : embColumnInfo.getColumns()) {
                        entityColumns.add(columnInfo.getColumnName());
                        alterColumn(alterTableOptions, schema, columnInfo, updated);
                    }
                }

                // delete columns
                for (ColumnSchema columnSchema : schema.getColumns()) {
                    // if not in tableInfo and not a key then delete
                    if (!entityColumns.contains(columnSchema.getName()) && !columnSchema.isKey()) {
                        alterTableOptions.dropColumn(columnSchema.getName());
                        updated.set(true);
                    }
                }

                if (updated.get()) {
                    client.alterTable(tableInfo.getTableName(), alterTableOptions);
                }
            }
        } catch (Exception e) {
            logger.error("Error while updating tables, Caused by: " + e.getMessage());
            throw new KunderaException("Error while updating tables, Caused by: " + e.getMessage());
        }
    }
}

From source file:com.spotify.helios.testing.TemporaryJob.java

private void awaitUp(final String host) throws TimeoutException {
    final TemporaryJobReports.Step startContainer = reportWriter.step("start container")
            .tag("jobId", job.getId()).tag("host", host).tag("image", job.getImage());
    try {//from w  ww.j  a va  2s  .  c  om
        final AtomicBoolean messagePrinted = new AtomicBoolean(false);
        final TaskStatus status = Polling.awaitUnchecked(deployTimeoutMillis, MILLISECONDS,
                job.getId() + " was not up within %d %s", new Callable<TaskStatus>() {
                    @Override
                    public TaskStatus call() throws Exception {
                        final JobStatus status = Futures.getUnchecked(client.jobStatus(job.getId()));
                        if (status == null) {
                            log.debug("Job status not available");
                            return null;
                        }
                        final TaskStatus taskStatus = status.getTaskStatuses().get(host);
                        if (taskStatus == null) {
                            log.debug("Task status not available on {}", host);
                            return null;
                        }

                        if (!messagePrinted.get() && !isNullOrEmpty(jobDeployedMessageFormat)
                                && !isNullOrEmpty(taskStatus.getContainerId())) {
                            outputDeployedMessage(host, taskStatus.getContainerId());
                            messagePrinted.set(true);
                        }

                        verifyHealthy(host, taskStatus);

                        final TaskStatus.State state = taskStatus.getState();
                        log.info("Job state of {}: {}", job.getImage(), state);

                        if (state == TaskStatus.State.RUNNING) {
                            return taskStatus;
                        }

                        return null;
                    }
                });

        statuses.put(host, status);

        startContainer.markSuccess();
    } finally {
        startContainer.finish();
    }

    final TemporaryJobReports.Step probe = reportWriter.step("probe").tag("jobId", job.getId()).tag("host",
            host);
    try {
        for (final String port : waitPorts) {
            awaitPort(port, host);
        }

        probe.markSuccess();
    } finally {
        probe.finish();
    }
}

From source file:org.apache.jackrabbit.core.integration.InterruptedQueryTest.java

@Test
public void testQuery() throws Exception {
    if (Constants.WINDOWS) {
        return;//from www  .  ja  v  a 2  s.  c  o  m
    }
    for (int i = 0; i < 100; i++) {
        session.getRootNode().addNode("node" + i, "nt:unstructured");
    }
    session.save();
    final QueryManager qm = session.getWorkspace().getQueryManager();
    final AtomicBoolean stop = new AtomicBoolean(false);
    final List<Exception> exceptions = Collections.synchronizedList(new ArrayList<Exception>());
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!stop.get() && exceptions.isEmpty()) {
                try {
                    // execute query
                    String stmt = "//*[@jcr:primaryType='nt:unstructured']";
                    qm.createQuery(stmt, Query.XPATH).execute();
                } catch (RepositoryException e) {
                    if (Constants.SUN_OS) {
                        // on Solaris it's OK when the root cause
                        // of the exception is an InterruptedIOException
                        // the underlying file is not closed
                        Throwable t = e;
                        while (t.getCause() != null) {
                            t = t.getCause();
                        }
                        if (!(t instanceof InterruptedIOException)) {
                            exceptions.add(e);
                        }
                    } else {
                        exceptions.add(e);
                    }
                }
            }
        }
    });
    t.start();
    for (int i = 0; i < 200 && t.isAlive(); i++) {
        t.interrupt();
        Thread.sleep((long) (100.0 * Math.random()));
    }
    stop.set(true);
    t.join();
    if (!exceptions.isEmpty()) {
        throw exceptions.get(0);
    }
}

From source file:com.netflix.curator.TestSessionFailRetryLoop.java

@Test
public void testRetryStatic() throws Exception {
    Timing timing = new Timing();
    final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(),
            timing.session(), timing.connection(), null, new RetryOneTime(1));
    SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.RETRY);
    retryLoop.start();/*from   w w  w . j  ava2 s .  c  om*/
    try {
        client.start();
        final AtomicBoolean secondWasDone = new AtomicBoolean(false);
        final AtomicBoolean firstTime = new AtomicBoolean(true);
        SessionFailRetryLoop.callWithRetry(client, SessionFailRetryLoop.Mode.RETRY, new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                RetryLoop.callWithRetry(client, new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        if (firstTime.compareAndSet(true, false)) {
                            Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                            KillSession.kill(client.getZooKeeper(), server.getConnectString());
                            client.getZooKeeper();
                            client.blockUntilConnectedOrTimedOut();
                        }

                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                        return null;
                    }
                });

                RetryLoop.callWithRetry(client, new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        Assert.assertFalse(firstTime.get());
                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                        secondWasDone.set(true);
                        return null;
                    }
                });
                return null;
            }
        });

        Assert.assertTrue(secondWasDone.get());
    } finally {
        retryLoop.close();
        IOUtils.closeQuietly(client);
    }
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessMutexBase.java

@Test
public void testReentrantSingleLock() throws Exception {
    final int THREAD_QTY = 10;

    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();/*from   www  .j  a v a  2 s  .c  o  m*/
    try {
        final AtomicBoolean hasLock = new AtomicBoolean(false);
        final AtomicBoolean isFirst = new AtomicBoolean(true);
        final Semaphore semaphore = new Semaphore(1);
        final InterProcessLock mutex = makeLock(client);

        List<Future<Object>> threads = Lists.newArrayList();
        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < THREAD_QTY; ++i) {
            Future<Object> t = service.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    semaphore.acquire();
                    mutex.acquire();
                    Assert.assertTrue(hasLock.compareAndSet(false, true));
                    try {
                        if (isFirst.compareAndSet(true, false)) {
                            semaphore.release(THREAD_QTY - 1);
                            while (semaphore.availablePermits() > 0) {
                                Thread.sleep(100);
                            }
                        } else {
                            Thread.sleep(100);
                        }
                    } finally {
                        mutex.release();
                        hasLock.set(false);
                    }
                    return null;
                }
            });
            threads.add(t);
        }

        for (Future<Object> t : threads) {
            t.get();
        }
    } finally {
        client.close();
    }
}

From source file:org.apache.tez.dag.app.TestMockDAGAppMaster.java

@Test(timeout = 100000)
public void testConcurrencyLimit() throws Exception {
    // the test relies on local mode behavior of launching a new container per task.
    // so task concurrency == container concurrency
    TezConfiguration tezconf = new TezConfiguration(defaultConf);

    final int concurrencyLimit = 5;
    MockTezClient tezClient = new MockTezClient("testMockAM", tezconf, true, null, null, null, null, false,
            false, concurrencyLimit * 4, 1000);

    tezClient.start();//from  www.  j a  v a2  s.c  o  m

    MockDAGAppMaster mockApp = tezClient.getLocalClient().getMockApp();
    MockContainerLauncher mockLauncher = mockApp.getContainerLauncher();
    mockLauncher.startScheduling(false);

    final AtomicInteger concurrency = new AtomicInteger(0);
    final AtomicBoolean exceededConcurrency = new AtomicBoolean(false);
    mockApp.containerDelegate = new ContainerDelegate() {
        @Override
        public void stop(ContainerStopRequest event) {
            concurrency.decrementAndGet();
        }

        @Override
        public void launch(ContainerLaunchRequest event) {
            int maxConc = concurrency.incrementAndGet();
            if (maxConc > concurrencyLimit) {
                exceededConcurrency.set(true);
            }
            System.out.println("Launched: " + maxConc);
        }
    };
    DAG dag = DAG.create("testConcurrencyLimit");
    Vertex vA = Vertex.create("A", ProcessorDescriptor.create("Proc.class"), 20)
            .setConf(TezConfiguration.TEZ_AM_VERTEX_MAX_TASK_CONCURRENCY, String.valueOf(concurrencyLimit));
    dag.addVertex(vA);

    mockLauncher.startScheduling(true);
    DAGClient dagClient = tezClient.submitDAG(dag);
    dagClient.waitForCompletion();
    Assert.assertEquals(DAGStatus.State.SUCCEEDED, dagClient.getDAGStatus(null).getState());
    Assert.assertFalse(exceededConcurrency.get());
    tezClient.stop();
}

From source file:com.tascape.qa.th.android.driver.App.java

/**
 * The method starts a GUI to let an user inspect element tree and take screenshot when the user is interacting
 * with the app-under-test manually. Please make sure to set timeout long enough for manual interaction.
 *
 * @param timeoutMinutes timeout in minutes to fail the manual steps
 *
 * @throws Exception if case of error/*from ww  w. jav  a  2  s  . co  m*/
 */
public void interactManually(int timeoutMinutes) throws Exception {
    LOG.info("Start manual UI interaction");
    long end = System.currentTimeMillis() + timeoutMinutes * 60000L;

    AtomicBoolean visible = new AtomicBoolean(true);
    AtomicBoolean pass = new AtomicBoolean(false);
    String tName = Thread.currentThread().getName() + "m";
    SwingUtilities.invokeLater(() -> {
        JDialog jd = new JDialog((JFrame) null, "Manual Device UI Interaction - " + device.getProductDetail());
        jd.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

        JPanel jpContent = new JPanel(new BorderLayout());
        jd.setContentPane(jpContent);
        jpContent.setPreferredSize(new Dimension(1088, 828));
        jpContent.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JPanel jpInfo = new JPanel();
        jpContent.add(jpInfo, BorderLayout.PAGE_START);
        jpInfo.setLayout(new BorderLayout());
        {
            JButton jb = new JButton("PASS");
            jb.setForeground(Color.green.darker());
            jb.setFont(jb.getFont().deriveFont(Font.BOLD));
            jpInfo.add(jb, BorderLayout.LINE_START);
            jb.addActionListener(event -> {
                pass.set(true);
                jd.dispose();
                visible.set(false);
            });
        }
        {
            JButton jb = new JButton("FAIL");
            jb.setForeground(Color.red);
            jb.setFont(jb.getFont().deriveFont(Font.BOLD));
            jpInfo.add(jb, BorderLayout.LINE_END);
            jb.addActionListener(event -> {
                pass.set(false);
                jd.dispose();
                visible.set(false);
            });
        }

        JLabel jlTimeout = new JLabel("xxx seconds left", SwingConstants.CENTER);
        jpInfo.add(jlTimeout, BorderLayout.CENTER);
        jpInfo.add(jlTimeout, BorderLayout.CENTER);
        new SwingWorker<Long, Long>() {
            @Override
            protected Long doInBackground() throws Exception {
                while (System.currentTimeMillis() < end) {
                    Thread.sleep(1000);
                    long left = (end - System.currentTimeMillis()) / 1000;
                    this.publish(left);
                }
                return 0L;
            }

            @Override
            protected void process(List<Long> chunks) {
                Long l = chunks.get(chunks.size() - 1);
                jlTimeout.setText(l + " seconds left");
                if (l < 850) {
                    jlTimeout.setForeground(Color.red);
                }
            }
        }.execute();

        JPanel jpResponse = new JPanel(new BorderLayout());
        JPanel jpProgress = new JPanel(new BorderLayout());
        jpResponse.add(jpProgress, BorderLayout.PAGE_START);

        JTextArea jtaJson = new JTextArea();
        jtaJson.setEditable(false);
        jtaJson.setTabSize(4);
        Font font = jtaJson.getFont();
        jtaJson.setFont(new Font("Courier New", font.getStyle(), font.getSize()));

        JTree jtView = new JTree();

        JTabbedPane jtp = new JTabbedPane();
        jtp.add("tree", new JScrollPane(jtView));
        jtp.add("json", new JScrollPane(jtaJson));

        jpResponse.add(jtp, BorderLayout.CENTER);

        JPanel jpScreen = new JPanel();
        jpScreen.setMinimumSize(new Dimension(200, 200));
        jpScreen.setLayout(new BoxLayout(jpScreen, BoxLayout.PAGE_AXIS));
        JScrollPane jsp1 = new JScrollPane(jpScreen);
        jpResponse.add(jsp1, BorderLayout.LINE_START);

        JPanel jpJs = new JPanel(new BorderLayout());
        JTextArea jtaJs = new JTextArea();
        jpJs.add(new JScrollPane(jtaJs), BorderLayout.CENTER);

        JSplitPane jSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jpResponse, jpJs);
        jSplitPane.setResizeWeight(0.88);
        jpContent.add(jSplitPane, BorderLayout.CENTER);

        JPanel jpLog = new JPanel();
        jpLog.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
        jpLog.setLayout(new BoxLayout(jpLog, BoxLayout.LINE_AXIS));

        JCheckBox jcbTap = new JCheckBox("Enable Click", null, false);
        jpLog.add(jcbTap);
        jpLog.add(Box.createHorizontalStrut(8));

        JButton jbLogUi = new JButton("Log Screen");
        jpResponse.add(jpLog, BorderLayout.PAGE_END);
        {
            jpLog.add(jbLogUi);
            jbLogUi.addActionListener((ActionEvent event) -> {
                jtaJson.setText("waiting for screenshot...");
                Thread t = new Thread(tName) {
                    @Override
                    public void run() {
                        LOG.debug("\n\n");
                        try {
                            WindowHierarchy wh = device.loadWindowHierarchy();
                            jtView.setModel(getModel(wh));

                            jtaJson.setText("");
                            jtaJson.append(wh.root.toJson().toString(2));
                            jtaJson.append("\n");

                            File png = device.takeDeviceScreenshot();
                            BufferedImage image = ImageIO.read(png);

                            int w = device.getDisplayWidth();
                            int h = device.getDisplayHeight();

                            BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
                            Graphics2D g2 = resizedImg.createGraphics();
                            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                            g2.drawImage(image, 0, 0, w, h, null);
                            g2.dispose();

                            JLabel jLabel = new JLabel(new ImageIcon(resizedImg));
                            jpScreen.removeAll();
                            jsp1.setPreferredSize(new Dimension(w + 30, h));
                            jpScreen.add(jLabel);

                            jLabel.addMouseListener(new MouseAdapter() {
                                @Override
                                public void mouseClicked(MouseEvent e) {
                                    LOG.debug("clicked at {},{}", e.getPoint().getX(), e.getPoint().getY());
                                    if (jcbTap.isSelected()) {
                                        device.click(e.getPoint().x, e.getPoint().y);
                                        device.waitForIdle();
                                        jbLogUi.doClick();
                                    }
                                }
                            });
                        } catch (Exception ex) {
                            LOG.error("Cannot log screen", ex);
                            jtaJson.append("Cannot log screen");
                        }
                        jtaJson.append("\n\n\n");
                        LOG.debug("\n\n");

                        jd.setSize(jd.getBounds().width + 1, jd.getBounds().height + 1);
                        jd.setSize(jd.getBounds().width - 1, jd.getBounds().height - 1);
                    }
                };
                t.start();
            });
        }
        jpLog.add(Box.createHorizontalStrut(38));
        {
            JButton jbLogMsg = new JButton("Log Message");
            jpLog.add(jbLogMsg);
            JTextField jtMsg = new JTextField(10);
            jpLog.add(jtMsg);
            jtMsg.addFocusListener(new FocusListener() {
                @Override
                public void focusLost(final FocusEvent pE) {
                }

                @Override
                public void focusGained(final FocusEvent pE) {
                    jtMsg.selectAll();
                }
            });
            jtMsg.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(java.awt.event.KeyEvent e) {
                    if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
                        jbLogMsg.doClick();
                    }
                }
            });
            jbLogMsg.addActionListener(event -> {
                Thread t = new Thread(tName) {
                    @Override
                    public void run() {
                        String msg = jtMsg.getText();
                        if (StringUtils.isNotBlank(msg)) {
                            LOG.info("{}", msg);
                            jtMsg.selectAll();
                        }
                    }
                };
                t.start();
                try {
                    t.join();
                } catch (InterruptedException ex) {
                    LOG.error("Cannot take screenshot", ex);
                }
                jtMsg.requestFocus();
            });
        }
        jpLog.add(Box.createHorizontalStrut(38));
        {
            JButton jbClear = new JButton("Clear");
            jpLog.add(jbClear);
            jbClear.addActionListener(event -> {
                jtaJson.setText("");
            });
        }

        JPanel jpAction = new JPanel();
        jpContent.add(jpAction, BorderLayout.PAGE_END);
        jpAction.setLayout(new BoxLayout(jpAction, BoxLayout.LINE_AXIS));
        jpJs.add(jpAction, BorderLayout.PAGE_END);

        jd.pack();
        jd.setVisible(true);
        jd.setLocationRelativeTo(null);

        jbLogUi.doClick();
    });

    while (visible.get()) {
        if (System.currentTimeMillis() > end) {
            LOG.error("Manual UI interaction timeout");
            break;
        }
        Thread.sleep(500);
    }

    if (pass.get()) {
        LOG.info("Manual UI Interaction returns PASS");
    } else {
        Assert.fail("Manual UI Interaction returns FAIL");
    }
}

From source file:org.apache.bookkeeper.bookie.CreateNewLogTest.java

@Test
public void testLockConsistency() throws Exception {
    ServerConfiguration conf = TestBKConfiguration.newServerConfiguration();

    conf.setLedgerDirNames(ledgerDirs);// w w  w .j a va 2 s  .  co m
    conf.setEntryLogFilePreAllocationEnabled(false);
    conf.setEntryLogPerLedgerEnabled(true);
    conf.setMaximumNumberOfActiveEntryLogs(5);

    CountDownLatch latch = new CountDownLatch(1);
    AtomicInteger count = new AtomicInteger(0);

    /*
     * Inject wait operation in 'getWritableLedgerDirsForNewLog' method of
     * ledgerDirsManager. getWritableLedgerDirsForNewLog will be called when
     * entryLogManager.createNewLog is called.
     */
    LedgerDirsManager ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(),
            new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())) {
        /*
         * getWritableLedgerDirsForNewLog is called for the first time, it
         * will await on 'latch' latch before calling super
         * getWritableLedgerDirsForNewLog.
         */
        @Override
        public List<File> getWritableLedgerDirsForNewLog() throws NoWritableLedgerDirException {
            if (count.incrementAndGet() == 1) {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    LOG.error("Got InterruptedException while awaiting for latch countdown", e);
                }
            }
            return super.getWritableLedgerDirsForNewLog();
        }
    };

    EntryLogger el = new EntryLogger(conf, ledgerDirsManager);
    EntryLogManagerForEntryLogPerLedger entryLogManager = (EntryLogManagerForEntryLogPerLedger) el
            .getEntryLogManager();

    long firstLedgerId = 100L;
    AtomicBoolean newLogCreated = new AtomicBoolean(false);

    Assert.assertFalse("EntryLogManager cacheMap should not contain entry for firstLedgerId",
            entryLogManager.getCacheAsMap().containsKey(firstLedgerId));
    Assert.assertEquals("Value of the count should be 0", 0, count.get());
    /*
     * In a new thread, create newlog for 'firstLedgerId' and then set
     * 'newLogCreated' to true. Since this is the first createNewLog call,
     * it is going to be blocked untill latch is countdowned to 0.
     */
    new Thread() {
        @Override
        public void run() {
            try {
                entryLogManager.createNewLog(firstLedgerId);
                newLogCreated.set(true);
            } catch (IOException e) {
                LOG.error("Got IOException while creating new log", e);
            }
        }
    }.start();

    /*
     * Wait until entry for 'firstLedgerId' is created in cacheMap. It will
     * be created because in the other thread createNewLog is called.
     */
    while (!entryLogManager.getCacheAsMap().containsKey(firstLedgerId)) {
        Thread.sleep(200);
    }
    Lock firstLedgersLock = entryLogManager.getLock(firstLedgerId);

    /*
     * since 'latch' is not counteddown, newlog should not be created even
     * after waitign for 2 secs.
     */
    Thread.sleep(2000);
    Assert.assertFalse("New log shouldn't have created", newLogCreated.get());

    /*
     * create MaximumNumberOfActiveEntryLogs of entrylogs and do cache
     * cleanup, so that the earliest entry from cache will be removed.
     */
    for (int i = 1; i <= conf.getMaximumNumberOfActiveEntryLogs(); i++) {
        entryLogManager.createNewLog(firstLedgerId + i);
    }
    entryLogManager.doEntryLogMapCleanup();
    Assert.assertFalse("Entry for that ledger shouldn't be there",
            entryLogManager.getCacheAsMap().containsKey(firstLedgerId));

    /*
     * now countdown the latch, so that the other thread can make progress
     * with createNewLog and since this entry is evicted from cache,
     * entrylog of the newly created entrylog will be added to
     * rotatedentrylogs.
     */
    latch.countDown();
    while (!newLogCreated.get()) {
        Thread.sleep(200);
    }
    while (entryLogManager.getRotatedLogChannels().size() < 1) {
        Thread.sleep(200);
    }

    /*
     * Entry for 'firstLedgerId' is removed from cache, but even in this
     * case when we get lock for the 'firstLedgerId' it should be the same
     * as we got earlier.
     */
    Lock lockForThatLedgerAfterRemoval = entryLogManager.getLock(firstLedgerId);
    Assert.assertEquals("For a given ledger lock should be the same before and after removal", firstLedgersLock,
            lockForThatLedgerAfterRemoval);
}