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:nlp.mediawiki.parser.MultistreamBzip2XmlDumpParser.java

@Override
public void run() {
    final AtomicBoolean terminate = new AtomicBoolean(false);
    final Logger logger = LoggerFactory.getLogger(MultistreamBzip2XmlDumpParser.class);
    //1. Start all worker threads
    for (int i = 0; i < workers.length; i++) {
        workers[i] = new Worker();
        workers[i].setName("Dump Worker " + i);
    }//from   w  w w. java  2s.  c  o m

    //Add an uncaught exception handler and allow for a graceful shutdown.
    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            logger.error("Fatal error in thread {}, terminating...", th.getName(), ex);
            for (Worker worker : workers) {
                worker.interrupt();
            }
            terminate.set(true);
        }
    };

    for (Worker worker : workers) {
        worker.setUncaughtExceptionHandler(h);
        worker.start();
    }

    //2. Seed them with data until there is no more
    PageBlock data;
    while ((data = pageReader.next()) != null && !terminate.get()) {
        try {
            blocks.put(data);
        } catch (InterruptedException e) {
            logger.error("Data put interrupted", e);
            break;
        }
    }

    for (int i = 0; i < workers.length; i++) {
        try {
            blocks.put(new PageBlock(null, null));
        } catch (InterruptedException e) {
            logger.info("Termination interrupted", e);
            break;
        }
    }

    //3. Await termination of all workers
    for (Worker worker : workers) {
        try {
            worker.join();
        } catch (InterruptedException e) {
            logger.error("Worker {} thread interrupted.", worker.getName(), e);
        }
    }

    output(Collections.<Page>emptyList());
}

From source file:com.arpnetworking.metrics.impl.ApacheHttpSinkTest.java

@Test
public void testSafeSleep() throws InterruptedException {
    final AtomicBoolean value = new AtomicBoolean(false);
    final Thread thread = new Thread(() -> {
        // Value will not be set if safe sleep throws or is not interrupted.
        ApacheHttpSink.safeSleep(500);//  ww w  .  j  a  v  a  2s .co  m
        value.set(true);
    });

    thread.start();
    Thread.sleep(100);
    thread.interrupt();
    thread.join(600);

    Assert.assertFalse(thread.isAlive());
    Assert.assertTrue(value.get());
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.TenantRoutingAuthenticationComponentFacade.java

/**
 *
 * {@inheritDoc}//from  w  w w . j a  v a 2s  . c  om
 */
@Override
protected boolean implementationAllowsGuestLogin() {
    final AtomicBoolean guestLoginAllowed = new AtomicBoolean(false);

    LOGGER.debug("Checking guestUserAuthenticationAllowed for enabled tenants (until first supporting tenant)");
    for (final String tenantDomain : this.enabledTenants) {
        if (!guestLoginAllowed.get()) {
            if (TenantUtil.DEFAULT_TENANT.equals(tenantDomain)
                    || (this.tenantAdminService.existsTenant(tenantDomain)
                            && this.tenantAdminService.isEnabledTenant(tenantDomain))) {
                final AuthenticationComponent authenticationComponent = TenantBeanUtils.getBeanForTenant(
                        this.applicationContext, this.beanName, tenantDomain, AuthenticationComponent.class);
                final boolean guestUserAuthenticationAllowed = authenticationComponent
                        .guestUserAuthenticationAllowed();
                LOGGER.trace("Tenant {} allows guest user authentication: {}", tenantDomain,
                        guestUserAuthenticationAllowed);
                guestLoginAllowed.set(guestUserAuthenticationAllowed);
            }
        }
    }
    LOGGER.debug("Component allowed guest authentication: {}", guestLoginAllowed.get());

    return guestLoginAllowed.get();
}

From source file:com.gargoylesoftware.js.CodeStyleTest.java

private boolean isSvnPropertiesDefined(final File file) {
    try {/*from  w  w  w  .  j  av a 2s. co m*/
        final AtomicBoolean eol = new AtomicBoolean();
        svnWCClient_.doGetProperty(file, null, SVNRevision.WORKING, SVNRevision.WORKING, SVNDepth.EMPTY,
                new ISVNPropertyHandler() {

                    @Override
                    public void handleProperty(final long revision, final SVNPropertyData property) {
                        // nothing to do
                    }

                    @Override
                    public void handleProperty(final SVNURL url, final SVNPropertyData property) {
                        // nothing to do
                    }

                    @Override
                    public void handleProperty(final File path, final SVNPropertyData property) {
                        final String name = property.getName();
                        final String value = property.getValue().getString();
                        if ("svn:eol-style".equals(name) && "native".equals(value)) {
                            eol.set(true);
                        }
                    }
                }, null);

        final String fileName = file.getName().toLowerCase(Locale.ROOT);

        for (final String extension : EOL_EXTENSIONS_) {
            if (fileName.endsWith(extension)) {
                return eol.get();
            }
        }
        return true;
    } catch (final Exception e) {
        //nothing
    }
    final String path = file.getAbsolutePath();
    // automatically generated and is outside SVN control
    return (path.contains("jQuery") && path.contains("WEB-INF") && path.contains("cgi"))
            || (path.contains("jQuery") && path.contains("csp.log"));
}

From source file:org.zodiark.subscriber.SubscriberTest.java

@Test(enabled = false)
public void sucessfulRequestForAction() throws IOException, InterruptedException {
    final CountDownLatch completed = new CountDownLatch(1);

    final ZodiarkClient wowzaClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch connected = new CountDownLatch(1);
    final AtomicReference<String> uuid = new AtomicReference<>();
    final AtomicReference<String> paths = new AtomicReference<>();

    // =============== Wowza

    paths.set("");
    wowzaClient.handler(new OnEnvelopHandler() {
        @Override//ww  w .  jav a 2s.  c o  m
        public boolean onEnvelop(Envelope e) throws IOException {

            Message m = e.getMessage();
            switch (m.getPath()) {
            case Paths.WOWZA_CONNECT:
                // Connected. Listen
                uuid.set(e.getUuid());
                break;
            case Paths.SERVER_VALIDATE_OK:
                Envelope publisherOk = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(paths.get()), e.getMessage().getData()));
                wowzaClient.send(publisherOk);
                break;
            case Paths.WOWZA_OBFUSCATE:
                WowzaMessage wm = mapper.readValue(m.getData(), WowzaMessage.class);
                Envelope ok = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(Paths.WOWZA_OBFUSCATE_OK), e.getMessage().getData()));
                System.out.println("Obfuscating Subscribers");
                wowzaClient.send(ok);
            case Paths.WOWZA_DEOBFUSCATE:
                wm = mapper.readValue(m.getData(), WowzaMessage.class);
                System.out.println("De-obfuscating Subscribers");
                ok = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(Paths.WOWZA_DEOBFUSCATE_OK), e.getMessage().getData()));
                wowzaClient.send(ok);
            default:
                // ERROR
            }

            connected.countDown();
            return false;
        }
    }).open();

    Envelope wowzaConnect = Envelope.newClientToServerRequest(new Message(new Path(Paths.WOWZA_CONNECT),
            mapper.writeValueAsString(new UserPassword("wowza", "bar"))));
    wowzaClient.send(wowzaConnect);
    connected.await();

    // ================ Publisher

    final AtomicReference<PublisherResults> answer = new AtomicReference<>();
    final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> publisherUUID = new AtomicReference<>();
    publisherClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
            publisherUUID.set(e.getUuid());
            latch.countDown();
            return true;
        }
    }).open();

    // ================ Publisher create the session

    Envelope createSessionMessage = Envelope.newClientToServerRequest(
            new Message(new Path(""), mapper.writeValueAsString(new UserPassword("publisherex", "bar"))));
    createSessionMessage.setFrom(new From(ActorValue.PUBLISHER));
    publisherClient.send(createSessionMessage);
    latch.await();
    assertEquals("OK", answer.get().getResults());
    answer.set(null);

    final CountDownLatch tlatch = new CountDownLatch(1);
    final AtomicReference<String> finalMessage = new AtomicReference<>();

    publisherClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {

            switch (e.getMessage().getPath()) {
            case Paths.BEGIN_STREAMING_SESSION:
                answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
                tlatch.countDown();
                break;
            case Paths.PUBLISHER_ACTION_ACCEPT:
                Action a = mapper.readValue(e.getMessage().getData(), Action.class);
                Envelope publisherOk = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(Paths.ZODIARK_ACTION_ACCEPTED), e.getMessage().getData()));
                publisherClient.send(publisherOk);
                break;
            case Paths.ACTION_START:
                // Start action
                PublisherResults results = mapper.readValue(e.getMessage().getData(), PublisherResults.class);
                System.out.println("==> Start Action " + results.getResults());

                publisherOk = Envelope.newClientToServerRequest(e.getUuid(),
                        new Message(new Path(Paths.ACTION_START_OK), e.getMessage().getData()));
                publisherClient.send(publisherOk);
                break;
            case Paths.ACTION_TIMER:
                Time t = mapper.readValue(e.getMessage().getData(), Time.class);
                System.out.println("Publisher ===>" + t);
                break;
            case Paths.ACTION_COMPLETED:
                results = mapper.readValue(e.getMessage().getData(), PublisherResults.class);
                System.out.println("Publisher Action completed");
                completed.countDown();
                break;
            case Paths.PUBLISHER_ABOUT_READY:
                results = mapper.readValue(e.getMessage().getData(), PublisherResults.class);

                finalMessage.set(results.getResults());
                break;
            }
            return false;
        }
    });

    // ================ Prepare for streaming, handshake with Wowza

    Envelope startStreamingSession = Envelope
            .newClientToServerRequest(new Message(new Path(Paths.VALIDATE_PUBLISHER_STREAMING_SESSION),
                    mapper.writeValueAsString(new WowzaUUID(uuid.get()))));
    createSessionMessage.setFrom(new From(ActorValue.PUBLISHER));
    publisherClient.send(startStreamingSession);

    tlatch.await();

    assertEquals("OK", answer.get().getResults());

    // ================ Subscriber

    paths.set(Paths.JOIN_SUBSCRIBER_STREAMING_SESSION);
    final AtomicReference<SubscriberResults> sanswer = new AtomicReference<>();
    final ZodiarkClient subscriberClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch platch = new CountDownLatch(1);
    final AtomicReference<String> subscriberUUID = new AtomicReference<>();

    subscriberClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            sanswer.set(mapper.readValue(e.getMessage().getData(), SubscriberResults.class));
            subscriberUUID.set(e.getUuid());
            platch.countDown();
            return true;
        }
    }).open();

    // ================ Subscriber create the session

    createSessionMessage = Envelope.newClientToServerRequest(subscriberUUID.get(),
            new Message(new Path(Paths.DB_POST_SUBSCRIBER_SESSION_CREATE),
                    mapper.writeValueAsString(new UserPassword("123456", "bar"))));
    createSessionMessage.setFrom(new From(ActorValue.SUBSCRIBER));
    subscriberClient.send(createSessionMessage);
    platch.await();
    assertEquals("OK", sanswer.get().getResults());
    sanswer.set(null);

    final CountDownLatch elatch = new CountDownLatch(1);
    subscriberClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            sanswer.set(mapper.readValue(e.getMessage().getData(), SubscriberResults.class));
            elatch.countDown();
            return true;
        }
    });

    // ================ Join the Publisher Session

    StreamingRequest request = new StreamingRequestImpl(publisherUUID.get(), uuid.get());
    startStreamingSession = Envelope.newClientToServerRequest(subscriberUUID.get(), new Message(
            new Path(Paths.VALIDATE_SUBSCRIBER_STREAMING_SESSION), mapper.writeValueAsString(request)));
    startStreamingSession.setFrom(new From(ActorValue.SUBSCRIBER));
    subscriberClient.send(startStreamingSession);

    elatch.await();

    assertEquals("OK", sanswer.get().getResults());

    // ================ Ask for an Action the Publisher Session

    Action action = new Action();
    action.setPath("/action/doSomething");
    action.setData("{ \"foo\":\"bar\"");
    Envelope e = Envelope.newClientToServerRequest(subscriberUUID.get(),
            new Message(new Path(Paths.SUBSCRIBER_ACTION), mapper.writeValueAsString(action)));
    e.setFrom(new From(ActorValue.SUBSCRIBER));
    final CountDownLatch actionLatch = new CountDownLatch(1);
    final AtomicReference<Envelope> response = new AtomicReference<>();
    final AtomicBoolean timerCalled = new AtomicBoolean();
    subscriberClient.handler(new OnEnvelopHandler() {
        @Override
        public boolean onEnvelop(Envelope e) throws IOException {
            switch (e.getMessage().getPath()) {
            case Paths.MESSAGE_ACTION_VALIDATE:
                response.set(e);
                actionLatch.countDown();
                break;
            case Paths.ACTION_TIMER:
                Time t = mapper.readValue(e.getMessage().getData(), Time.class);
                System.out.println("Subscriber ===>" + t);
                timerCalled.set(true);
                break;
            case Paths.ACTION_COMPLETED:
                SubscriberResults results = mapper.readValue(e.getMessage().getData(), SubscriberResults.class);
                System.out.println("Action completed");
                break;
            }

            return false;
        }
    });
    subscriberClient.send(e);

    actionLatch.await();

    assertEquals(Paths.MESSAGE_ACTION_VALIDATE, response.get().getMessage().getPath());
    assertEquals("{\"results\":\"OK\",\"uuid\":null}", response.get().getMessage().getData());

    completed.await();

    assertTrue(timerCalled.get());
    assertEquals("READY", finalMessage.get());
}

From source file:com.alexholmes.hdfsslurper.Slurper.java

private void run() throws IOException, InterruptedException {

    FileSystemManager fileSystemManager = new FileSystemManager(config);

    log.info("event#Moving any files in work directory to error directory");

    fileSystemManager.moveWorkFilesToError();

    final List<WorkerThread> workerThreads = new ArrayList<WorkerThread>();
    for (int i = 1; i <= config.getNumThreads(); i++) {
        WorkerThread t = new WorkerThread(config, fileSystemManager, TimeUnit.MILLISECONDS, i);
        t.start();//w w  w .  j a  v  a  2  s .  c o m
        workerThreads.add(t);
    }

    final AtomicBoolean programmaticShutdown = new AtomicBoolean(false);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                if (programmaticShutdown.get()) {
                    log.info("event#JVM shutting down");
                } else {
                    log.info("event#External process signalled JVM shutdown, shutting down threads.");
                    log.info("event#This may take a few minutes until we let the threads complete ");
                    log.info("event#the current file being copied.");
                    for (WorkerThread workerThread : workerThreads) {
                        workerThread.shutdown();
                    }
                    log.info("event#Threads dead");
                }
            } catch (Throwable t) {
                log.error("event#Hit snag in shutdown hook", t);
            }

        }
    });

    log.info("event#Running");

    for (WorkerThread workerThread : workerThreads) {
        workerThread.join();
    }
    programmaticShutdown.set(true);
}

From source file:org.apache.hadoop.net.unix.TestDomainSocket.java

@Test(timeout = 180000)
public void testShutdown() throws Exception {
    final AtomicInteger bytesRead = new AtomicInteger(0);
    final AtomicBoolean failed = new AtomicBoolean(false);
    final DomainSocket[] socks = DomainSocket.socketpair();
    Runnable reader = new Runnable() {
        @Override//from  w ww  .  j  a  v a2s. co m
        public void run() {
            while (true) {
                try {
                    int ret = socks[1].getInputStream().read();
                    if (ret == -1)
                        return;
                    bytesRead.addAndGet(1);
                } catch (IOException e) {
                    DomainSocket.LOG.error("reader error", e);
                    failed.set(true);
                    return;
                }
            }
        }
    };
    Thread readerThread = new Thread(reader);
    readerThread.start();
    socks[0].getOutputStream().write(1);
    socks[0].getOutputStream().write(2);
    socks[0].getOutputStream().write(3);
    Assert.assertTrue(readerThread.isAlive());
    socks[0].shutdown();
    readerThread.join();
    Assert.assertFalse(failed.get());
    Assert.assertEquals(3, bytesRead.get());
    IOUtils.cleanup(null, socks);
}

From source file:com.google.dart.java2dart.Context.java

private void dontUseThisInFieldInitializers(CompilationUnit unit) {
    unit.accept(new RecursiveASTVisitor<Void>() {
        @Override/* w w w .ja v a  2 s. c  o  m*/
        public Void visitClassDeclaration(ClassDeclaration node) {
            processClass(node);
            return super.visitClassDeclaration(node);
        }

        private void addAssignmentsToBlock(Block block, Map<SimpleIdentifier, Expression> initializers) {
            int index = 0;
            for (Entry<SimpleIdentifier, Expression> entry : initializers.entrySet()) {
                block.getStatements().add(index++, expressionStatement(assignmentExpression(
                        propertyAccess(thisExpression(), entry.getKey()), TokenType.EQ, entry.getValue())));
            }
        }

        private void processClass(final ClassDeclaration classDeclaration) {
            final Map<SimpleIdentifier, Expression> thisInitializers = Maps.newLinkedHashMap();
            // find field initializers which use "this"
            classDeclaration.accept(new RecursiveASTVisitor<Void>() {
                @Override
                public Void visitVariableDeclaration(VariableDeclaration node) {
                    if (node.getParent().getParent() instanceof FieldDeclaration) {
                        if (hasThisExpression(node)) {
                            thisInitializers.put(node.getName(), node.getInitializer());
                            node.setInitializer(null);
                        }
                    }
                    return super.visitVariableDeclaration(node);
                }

                private boolean hasThisExpression(ASTNode node) {
                    final AtomicBoolean result = new AtomicBoolean();
                    node.accept(new GeneralizingASTVisitor<Void>() {
                        @Override
                        public Void visitThisExpression(ThisExpression node) {
                            result.set(true);
                            return super.visitThisExpression(node);
                        }
                    });
                    return result.get();
                }
            });
            // add field assignment for each "this" field initializer
            if (thisInitializers.isEmpty()) {
                return;
            }
            ConstructorDeclaration singleConstructor = null;
            boolean hasImpl = false;
            for (ClassMember classMember : classDeclaration.getMembers()) {
                if (classMember instanceof ConstructorDeclaration) {
                    singleConstructor = (ConstructorDeclaration) classMember;
                }
                if (classMember instanceof MethodDeclaration) {
                    MethodDeclaration method = (MethodDeclaration) classMember;
                    String methodName = method.getName().getName();
                    if (methodName.startsWith("_jtd_constructor_") && methodName.endsWith("_impl")) {
                        hasImpl = true;
                        Block block = ((BlockFunctionBody) method.getBody()).getBlock();
                        addAssignmentsToBlock(block, thisInitializers);
                    }
                }
            }
            // no "_impl", add assignments to the single constructor
            if (!hasImpl && singleConstructor != null) {
                Block block = ((BlockFunctionBody) singleConstructor.getBody()).getBlock();
                addAssignmentsToBlock(block, thisInitializers);
            }
            // no "_impl", generate default constructor
            if (singleConstructor == null) {
                Block block = block();
                addAssignmentsToBlock(block, thisInitializers);
                ConstructorDeclaration constructor = constructorDeclaration(classDeclaration.getName(), null,
                        formalParameterList(), null, blockFunctionBody(block));
                classDeclaration.getMembers().add(constructor);
            }
        }
    });
}

From source file:ch.cyberduck.core.pool.DefaultSessionPoolTest.java

@Test
public void testCheckReconnectSocketFailure() throws Exception {
    final AtomicBoolean interrupt = new AtomicBoolean();
    final Host bookmark = new Host(new TestProtocol());
    final TestLoginConnectionService connect = new TestLoginConnectionService() {
        @Override/*from   w w w  . j a  v  a 2s.co  m*/
        public boolean check(final Session<?> session, final Cache<Path> cache, final CancelCallback callback)
                throws BackgroundException {
            return true;
        }
    };
    final DefaultSessionPool pool = new DefaultSessionPool(connect,
            new DefaultVaultRegistry(new DisabledPasswordCallback()), PathCache.empty(),
            new DisabledTranscriptListener(), bookmark,
            new GenericObjectPool<Session>(new PooledSessionFactory(connect, new DisabledX509TrustManager(),
                    new DefaultX509KeyManager(), PathCache.empty(), bookmark,
                    new DefaultVaultRegistry(new DisabledPasswordCallback())) {
                @Override
                public Session create() {
                    return new NullSession(bookmark) {
                        @Override
                        public void interrupt() throws BackgroundException {
                            interrupt.set(true);
                            super.interrupt();
                        }
                    };
                }
            }));
    final Session<?> session = pool.borrow(BackgroundActionState.running);
    pool.release(session, new BackgroundException("m", new SocketException("m")));
    assertTrue(interrupt.get());
}

From source file:ch.cyberduck.core.pool.DefaultSessionPoolTest.java

@Test
public void testCheckReconnectApplicationFailure() throws Exception {
    final AtomicBoolean interrupt = new AtomicBoolean();
    final Host bookmark = new Host(new TestProtocol());
    final TestLoginConnectionService connect = new TestLoginConnectionService() {
        @Override/*  ww w.j  a  v  a 2s  . c o  m*/
        public boolean check(final Session<?> session, final Cache<Path> cache, final CancelCallback callback)
                throws BackgroundException {
            return true;
        }
    };
    final DefaultSessionPool pool = new DefaultSessionPool(connect,
            new DefaultVaultRegistry(new DisabledPasswordCallback()), PathCache.empty(),
            new DisabledTranscriptListener(), bookmark,
            new GenericObjectPool<Session>(new PooledSessionFactory(connect, new DisabledX509TrustManager(),
                    new DefaultX509KeyManager(), PathCache.empty(), bookmark,
                    new DefaultVaultRegistry(new DisabledPasswordCallback())) {
                @Override
                public Session create() {
                    return new NullSession(bookmark) {
                        @Override
                        public void interrupt() throws BackgroundException {
                            interrupt.set(true);
                            super.interrupt();
                        }
                    };
                }
            }));
    final Session<?> session = pool.borrow(BackgroundActionState.running);
    pool.release(session, new BackgroundException("m", "d"));
    assertFalse(interrupt.get());
}