Example usage for java.util.concurrent.atomic AtomicReference get

List of usage examples for java.util.concurrent.atomic AtomicReference get

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicReference get.

Prototype

public final V get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:com.networknt.openapi.JwtVerifyHandlerTest.java

@Test
public void testUnmatchedScopeInIdToken() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {//from   www .j a v a2s .c  o m
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v1/pets/111").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "Bearer eyJraWQiOiIxMDAiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ1cm46Y29tOm5ldHdvcmtudDpvYXV0aDI6djEiLCJhdWQiOiJ1cm46Y29tLm5ldHdvcmtudCIsImV4cCI6MTgwNTEzNjU1MSwianRpIjoiTVJiZHdlQ295eG13a2ZUM3lVWGloQSIsImlhdCI6MTQ4OTc3NjU1MSwibmJmIjoxNDg5Nzc2NDMxLCJ2ZXJzaW9uIjoiMS4wIiwidXNlcl9pZCI6ImVyaWMiLCJ1c2VyX3R5cGUiOiJFTVBMT1lFRSIsImNsaWVudF9pZCI6ImY3ZDQyMzQ4LWM2NDctNGVmYi1hNTJkLTRjNTc4NzQyMWU3MiIsInNjb3BlIjpbIkFUTVAxMDAwLnciLCJBVE1QMTAwMC5yIl19.VOEggO6UIMHNJLrxShGivCh7sGyHiz7h9FqDjlKwywGP9xKbVTTODy2-FitUaS1Y2vjiHlJ0TNyxmj1SO11YwYnJlW1zn-6vfKWKI70DyvRwsvSX_8Z2fj0jPUiBqezwKRtLCHSsmiEpMrW6YQHYw0qzZ9kkMhiH2uFpZNCekOQWL1piRn1xVQkUmeFiTDvJQESHadFzw-9x0klO7-SxgKeHHDroxnpbLv2j795oMTB1gM_wJP6HO_M-gK6N1Uh6zssfnbyFReRNWkhZFOp3Y8DvwpfKhqXIVGUc_5WsO9M-y66icClVNl5zwLSmjsrNtqZkmeBCwQ6skBnRLfMocQ");
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(403, statusCode);
    if (statusCode == 403) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10005", status.getCode());
    }
}

From source file:com.networknt.security.JwtVerifyHandlerTest.java

@Test
public void testUnmatchedScopeInIdToken() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {// w  ww .ja va2  s .  co m
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet/111").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "Bearer eyJraWQiOiIxMDAiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ1cm46Y29tOm5ldHdvcmtudDpvYXV0aDI6djEiLCJhdWQiOiJ1cm46Y29tLm5ldHdvcmtudCIsImV4cCI6MTgwNTEzNjU1MSwianRpIjoiTVJiZHdlQ295eG13a2ZUM3lVWGloQSIsImlhdCI6MTQ4OTc3NjU1MSwibmJmIjoxNDg5Nzc2NDMxLCJ2ZXJzaW9uIjoiMS4wIiwidXNlcl9pZCI6ImVyaWMiLCJ1c2VyX3R5cGUiOiJFTVBMT1lFRSIsImNsaWVudF9pZCI6ImY3ZDQyMzQ4LWM2NDctNGVmYi1hNTJkLTRjNTc4NzQyMWU3MiIsInNjb3BlIjpbIkFUTVAxMDAwLnciLCJBVE1QMTAwMC5yIl19.VOEggO6UIMHNJLrxShGivCh7sGyHiz7h9FqDjlKwywGP9xKbVTTODy2-FitUaS1Y2vjiHlJ0TNyxmj1SO11YwYnJlW1zn-6vfKWKI70DyvRwsvSX_8Z2fj0jPUiBqezwKRtLCHSsmiEpMrW6YQHYw0qzZ9kkMhiH2uFpZNCekOQWL1piRn1xVQkUmeFiTDvJQESHadFzw-9x0klO7-SxgKeHHDroxnpbLv2j795oMTB1gM_wJP6HO_M-gK6N1Uh6zssfnbyFReRNWkhZFOp3Y8DvwpfKhqXIVGUc_5WsO9M-y66icClVNl5zwLSmjsrNtqZkmeBCwQ6skBnRLfMocQ");
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(403, statusCode);
    if (statusCode == 403) {
        Status status = Config.getInstance().getMapper()
                .readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10005", status.getCode());
    }
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

/**
 * Requests all updates from each peer in the provided list of peers.
 * <p>/*from w w w.jav  a 2  s  .c  o  m*/
 * The returned future will be completed once at least one peer bootstraps this map or bootstrap requests to all peers
 * fail.
 *
 * @param peers the list of peers from which to request updates
 * @return a future to be completed once updates have been received from at least one peer
 */
private CompletableFuture<Void> requestBootstrapFromPeers(List<MemberId> peers) {
    if (peers.isEmpty()) {
        return CompletableFuture.completedFuture(null);
    }
    CompletableFuture<Void> future = new CompletableFuture<>();
    final int totalPeers = peers.size();
    AtomicBoolean successful = new AtomicBoolean();
    AtomicInteger totalCount = new AtomicInteger();
    AtomicReference<Throwable> lastError = new AtomicReference<>();

    // Iterate through all of the peers and send a bootstrap request. On the first peer that returns
    // a successful bootstrap response, complete the future. Otherwise, if no peers respond with any
    // successful bootstrap response, the future will be completed with the last exception.
    for (MemberId peer : peers) {
        requestBootstrapFromPeer(peer).whenComplete((result, error) -> {
            if (error == null) {
                if (successful.compareAndSet(false, true)) {
                    future.complete(null);
                } else if (totalCount.incrementAndGet() == totalPeers) {
                    Throwable e = lastError.get();
                    if (e != null) {
                        future.completeExceptionally(e);
                    }
                }
            } else {
                if (!successful.get() && totalCount.incrementAndGet() == totalPeers) {
                    future.completeExceptionally(error);
                } else {
                    lastError.set(error);
                }
            }
        });
    }
    return future;
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

private void createWithoutValidate(JsonObject data, RBatch redissonBatch,
        AsyncResultHandler<String> resultHandler) {
    AtomicReference<String> id = new AtomicReference<>();
    Async.waterfall().<String>task(this::newId).<String>task((i, t) -> {
        id.set(i);/* www . j  a v a  2  s .c  o  m*/
        ensureUniqueAndIndexing(id.get(), data, true, rs -> {
            if (rs.succeeded() && rs.result() == null) {
                t.handle(Future.succeededFuture());
            } else if (rs.result() != null) {
                t.handle(Future.failedFuture(new RepositoryException(rs.result())));
            } else {
                t.handle(Future.failedFuture(rs.cause()));
            }
        });
    }).<Boolean>task((rs, t) -> {
        persist(id.get(), data.put("id", id.get()), redissonBatch, t);
    }).run(run -> {
        resultHandler
                .handle(run.succeeded() ? Future.succeededFuture(id.get()) : Future.failedFuture(run.cause()));
    });
}

From source file:com.oasisfeng.nevo.decorators.media.MediaPlayerDecorator.java

@Override
protected void apply(final StatusBarNotificationEvo evolving) throws Exception {
    if (evolving.isClearable())
        return; // Just sticky notification, to reduce the overhead.
    final INotification n = evolving.notification();
    RemoteViews content_view = n.getBigContentView(); // Prefer big content view since it usually contains more actions
    if (content_view == null)
        content_view = n.getContentView();
    if (content_view == null)
        return;/*from www. j  a  v  a2s  .  c om*/
    final AtomicReference<IntentSender> sender_holder = new AtomicReference<>();
    final View views = content_view.apply(new ContextWrapper(this) {
        @Override
        public void startIntentSender(final IntentSender intent, final Intent fillInIntent, final int flagsMask,
                final int flagsValues, final int extraFlags) throws IntentSender.SendIntentException {
            startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, null);
        }

        @Override
        public void startIntentSender(final IntentSender intent, final Intent fillInIntent, final int flagsMask,
                final int flagsValues, final int extraFlags, final Bundle options)
                throws IntentSender.SendIntentException {
            sender_holder.set(intent);
        }
    }, null);
    if (!(views instanceof ViewGroup))
        return;

    final List<NotificationCompat.Action> actions = new ArrayList<>(8);
    findClickable((ViewGroup) views, new Predicate<View>() {
        @Override
        public boolean apply(final View v) {
            sender_holder.set(null);
            v.performClick(); // trigger startIntentSender() above
            final IntentSender sender = sender_holder.get();
            if (sender == null) {
                Log.w(TAG, v + " has OnClickListener but no PendingIntent in it.");
                return true;
            }

            final PendingIntent pending_intent = getPendingIntent(sender);
            if (v instanceof TextView) {
                final CharSequence text = ((TextView) v).getText();
                actions.add(new NotificationCompat.Action(0, text, pending_intent));
            } else if (v instanceof ImageView) {
                final int res = getImageViewResource((ImageView) v);
                CharSequence title = v.getContentDescription();
                if (title == null)
                    title = "<" + System.identityHashCode(v);
                actions.add(new NotificationCompat.Action(res, title, pending_intent));
            } else {
                CharSequence title = v.getContentDescription();
                if (title == null)
                    title = "<" + System.identityHashCode(v);
                actions.add(new NotificationCompat.Action(0, title, pending_intent));
            }
            return true;
        }
    });

    final Notification mirror;
    final String pkg = evolving.getPackageName();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        final Notification.Builder b = new Notification.Builder(createPackageContext(pkg, 0))
                .setContentTitle(n.extras().getCharSequence(NotificationCompat.EXTRA_TITLE))
                .setLargeIcon(n.getLargeIcon()).setSmallIcon(fixIconPkg(n.getSmallIcon(), pkg));
        for (final NotificationCompat.Action action : actions)
            b.addAction(new Action.Builder(Icon.createWithResource(pkg, action.getIcon()), action.getTitle(),
                    action.getActionIntent()).build());
        mirror = b.build();
    } else {
        final NotificationCompat.Builder b = new NotificationCompat.Builder(createPackageContext(pkg, 0))
                .setContentTitle(n.extras().getCharSequence(NotificationCompat.EXTRA_TITLE))
                .setLargeIcon(n.extras().getParcelable(NotificationCompat.EXTRA_LARGE_ICON).<Bitmap>get())
                .setSmallIcon(android.R.drawable.ic_media_play);
        for (final NotificationCompat.Action action : actions)
            b.addAction(action);
        mirror = b.build();
    }
    final NotificationManagerCompat nm = NotificationManagerCompat.from(this);
    nm.notify("M<" + evolving.getPackageName() + (evolving.getTag() != null ? ">" + evolving.getTag() : ">"),
            evolving.getId(), mirror);
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandlerTest.java

@Test
public void shouldFireKeepAlive() throws Exception {
    final AtomicInteger keepAliveEventCounter = new AtomicInteger();
    final AtomicReference<ChannelHandlerContext> ctxRef = new AtomicReference();

    ViewHandler testHandler = new ViewHandler(endpoint, responseRingBuffer, queue, false) {
        @Override//www  .  j  a  va 2 s  .  c  o  m
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            super.channelRegistered(ctx);
            ctxRef.compareAndSet(null, ctx);
        }

        @Override
        protected void onKeepAliveFired(ChannelHandlerContext ctx, CouchbaseRequest keepAliveRequest) {
            assertEquals(1, keepAliveEventCounter.incrementAndGet());
        }

        @Override
        protected void onKeepAliveResponse(ChannelHandlerContext ctx, CouchbaseResponse keepAliveResponse) {
            assertEquals(2, keepAliveEventCounter.incrementAndGet());
        }
    };
    EmbeddedChannel channel = new EmbeddedChannel(testHandler);

    //test idle event triggers a view keepAlive request and hook is called
    testHandler.userEventTriggered(ctxRef.get(), IdleStateEvent.FIRST_ALL_IDLE_STATE_EVENT);

    assertEquals(1, keepAliveEventCounter.get());
    assertTrue(queue.peek() instanceof ViewHandler.KeepAliveRequest);
    ViewHandler.KeepAliveRequest keepAliveRequest = (ViewHandler.KeepAliveRequest) queue.peek();

    //test responding to the request with http response is interpreted into a KeepAliveResponse and hook is called
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    channel.writeInbound(response);
    ViewHandler.KeepAliveResponse keepAliveResponse = keepAliveRequest.observable()
            .cast(ViewHandler.KeepAliveResponse.class).timeout(1, TimeUnit.SECONDS).toBlocking().single();

    assertEquals(2, keepAliveEventCounter.get());
    assertEquals(ResponseStatus.NOT_EXISTS, keepAliveResponse.status());
}

From source file:org.cerberus.launchcampaign.checkcampaign.CheckCampaignStatus.java

/**
 * Check all 5 seconds the status of campaign's execution. 
 * @param checkCampaign call method checkCampaign() all 5 seconds with parameter {@link ResultCIDto}.  
 *                   {@link ResultCIDto} contains all information of execution of campaing at the instant t
 * @param result call method result() when campaign execution is finish.
 *             {@link ResultCIDto} contains all information of execution at finish time
 * @throws Exception /*from w w  w . ja  v  a  2s .co  m*/
 */
public void execute(final CheckCampaignEvent checkCampaign, final ResultEvent result, final LogEvent logEvent)
        throws Exception {
    final ScheduledThreadPoolExecutor sch = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);

    final AtomicReference<Exception> exceptionOnThread = new AtomicReference<Exception>();

    sch.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            try {
                URL resultURL = new URL(urlCerberus + "/" + Constantes.URL_RESULT_CI + "?tag=" + tagCerberus);
                ResultCIDto resultDto = new ObjectMapper().readValue(resultURL, ResultCIDto.class);

                // condition to finish task
                if (!"PE".equals(resultDto.getResult())) {
                    result.result(resultDto);
                    sch.shutdown(); // when campaign is finish, we shutdown the schedule thread
                }

                if (!checkCampaign.checkCampaign(resultDto)) {
                    sch.shutdown();
                }
            } catch (SocketException e) {
                // do nothing during network problem. Wait the timeout to shutdown, and notify the error to logEvent
                logEvent.log("", e.getMessage() + "\n" + ExceptionUtils.getStackTrace(e));
            } catch (Exception e) {
                exceptionOnThread.set(e);
                sch.shutdown();
            }
        }
    }, 0, this.timeToRefreshCampaignStatus, TimeUnit.SECONDS);

    sch.awaitTermination(this.timeoutForCampaignExecution, TimeUnit.SECONDS);

    // pass exeption of thread to called method
    if (exceptionOnThread.get() != null) {
        throw exceptionOnThread.get();
    }
}

From source file:com.google.cloud.dns.testing.LocalDnsHelper.java

/**
 * Applies changes to a zone. Repeatedly tries until succeeds. Thread safe and deadlock safe.
 *///w  ww .j a va 2s. co m
private void applyExistingChange(String projectId, String zoneName, String changeId) {
    Change change = findChange(projectId, zoneName, changeId);
    if (change == null) {
        return; // no such change exists, nothing to do
    }
    ZoneContainer wrapper = findZone(projectId, zoneName);
    if (wrapper == null) {
        return; // no such zone exists; it might have been deleted by another thread
    }
    AtomicReference<ImmutableSortedMap<String, ResourceRecordSet>> dnsRecords = wrapper.dnsRecords();
    while (true) {
        // managed zone must have a set of records which is not null
        ImmutableSortedMap<String, ResourceRecordSet> original = dnsRecords.get();
        // the copy will be populated when handling deletions
        SortedMap<String, ResourceRecordSet> copy = new TreeMap<>();
        // apply deletions first
        List<ResourceRecordSet> deletions = change.getDeletions();
        if (deletions != null) {
            for (Map.Entry<String, ResourceRecordSet> entry : original.entrySet()) {
                if (!deletions.contains(entry.getValue())) {
                    copy.put(entry.getKey(), entry.getValue());
                }
            }
        } else {
            copy.putAll(original);
        }
        // apply additions
        List<ResourceRecordSet> additions = change.getAdditions();
        if (additions != null) {
            for (ResourceRecordSet addition : additions) {
                ResourceRecordSet rrset = new ResourceRecordSet();
                rrset.setName(addition.getName());
                rrset.setRrdatas(ImmutableList.copyOf(addition.getRrdatas()));
                rrset.setTtl(addition.getTtl());
                rrset.setType(addition.getType());
                String id = getUniqueId(copy.keySet());
                copy.put(id, rrset);
            }
        }
        boolean success = dnsRecords.compareAndSet(original, ImmutableSortedMap.copyOf(copy));
        if (success) {
            break; // success if no other thread modified the value in the meantime
        }
    }
    change.setStatus("done");
}

From source file:de.hybris.platform.test.ThreadPoolTest.java

@Test
public void testTransactionCleanUpSimple()
        throws InterruptedException, BrokenBarrierException, TimeoutException {
    final boolean flagBefore = Config.getBoolean("transaction.monitor.begin", false);
    Config.setParameter("transaction.monitor.begin", "true");
    ThreadPool pool = null;// w w w. ja  v  a  2s . c  o  m
    try {
        pool = new ThreadPool(Registry.getCurrentTenantNoFallback().getTenantID(), 1);

        final GenericObjectPool.Config config = new GenericObjectPool.Config();
        config.maxActive = 1;
        config.maxIdle = 1;
        config.maxWait = -1;
        config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        config.testOnBorrow = true;
        config.testOnReturn = true;
        config.timeBetweenEvictionRunsMillis = 30 * 1000; // keep idle threads for at most 30 sec
        pool.setConfig(config);

        final CyclicBarrier gate = new CyclicBarrier(2);
        final AtomicReference<Throwable> threadError = new AtomicReference<Throwable>();
        final AtomicReference<RecordingTransaction> threadTransaction = new AtomicReference<ThreadPoolTest.RecordingTransaction>();
        final PoolableThread thread1 = pool.borrowThread();
        thread1.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    final Transaction tx = new RecordingTransaction();
                    tx.activateAsCurrentTransaction();
                    tx.begin();
                    tx.begin(); // second time
                    tx.begin(); // third time
                    assertTrue(tx.isRunning());
                    assertEquals(3, tx.getOpenTransactionCount());
                    threadTransaction.set((RecordingTransaction) tx);
                    gate.await(10, TimeUnit.SECONDS);
                } catch (final Throwable t) {
                    threadError.set(t);
                }
            }
        });
        gate.await(10, TimeUnit.SECONDS);
        assertNull(threadError.get());
        // busy waiting for correct number of rollbacks - at the moment there is no hook for a better solution
        final RecordingTransaction tx = threadTransaction.get();
        final long maxWait = System.currentTimeMillis() + (15 * 1000);
        while (tx.rollbackCounter.get() < 3 && System.currentTimeMillis() < maxWait) {
            Thread.sleep(100);
        }
        assertEquals(3, tx.rollbackCounter.get());

        final PoolableThread thread2 = pool.borrowThread();
        assertNotSame(thread1, thread2);
    } finally {
        if (pool != null) {
            try {
                pool.close();
            } catch (final Exception e) {
                // can't help it
            }
        }
        Config.setParameter("transaction.monitor.begin", BooleanUtils.toStringTrueFalse(flagBefore));
    }
}

From source file:info.archinnov.achilles.embedded.ServerStarter.java

private void start(final TypedMap parameters) {
    if (isAlreadyRunning()) {
        log.debug("Cassandra is already running, not starting new one");
        return;/*w  w  w .  ja v  a  2s .c om*/
    }

    final String triggersDir = createTriggersFolder();

    log.info(" Random embedded Cassandra RPC port/Thrift port = {}",
            parameters.<Integer>getTyped(CASSANDRA_THRIFT_PORT));
    log.info(" Random embedded Cassandra Native port/CQL port = {}",
            parameters.<Integer>getTyped(CASSANDRA_CQL_PORT));
    log.info(" Random embedded Cassandra Storage port = {}",
            parameters.<Integer>getTyped(CASSANDRA_STORAGE_PORT));
    log.info(" Random embedded Cassandra Storage SSL port = {}",
            parameters.<Integer>getTyped(CASSANDRA_STORAGE_SSL_PORT));
    log.info(" Random embedded Cassandra Remote JMX port = {}",
            System.getProperty("com.sun.management.jmxremote.port", "null"));
    log.info(" Embedded Cassandra triggers directory = {}", triggersDir);

    log.info("Starting Cassandra...");

    System.setProperty("cassandra.triggers_dir", triggersDir);
    System.setProperty("cassandra-foreground", "true");
    System.setProperty("cassandra.embedded.concurrent.reads",
            parameters.getTypedOr(CASSANDRA_CONCURRENT_READS, 32).toString());
    System.setProperty("cassandra.embedded.concurrent.writes",
            parameters.getTypedOr(CASSANDRA_CONCURRENT_WRITES, 32).toString());
    System.setProperty("cassandra-foreground", "true");

    final boolean useUnsafeCassandra = parameters.getTyped(USE_UNSAFE_CASSANDRA_DAEMON);

    if (useUnsafeCassandra) {
        System.setProperty("cassandra-num-tokens", "1");
    }

    System.setProperty("cassandra.config.loader", "info.archinnov.achilles.embedded.AchillesCassandraConfig");

    final CountDownLatch startupLatch = new CountDownLatch(1);
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final AtomicReference<CassandraDaemon> daemonRef = new AtomicReference<>();
    executor.execute(() -> {
        if (useUnsafeCassandra) {
            LOGGER.warn(
                    "******* WARNING, starting unsafe embedded Cassandra deamon. This should be only used for unit testing or development and not for production !");
        }

        CassandraDaemon cassandraDaemon = useUnsafeCassandra == true ? new AchillesCassandraDaemon()
                : new CassandraDaemon();

        cassandraDaemon.completeSetup();
        cassandraDaemon.activate();
        daemonRef.getAndSet(cassandraDaemon);
        startupLatch.countDown();
    });

    try {
        startupLatch.await(30, SECONDS);
    } catch (InterruptedException e) {
        log.error("Timeout starting Cassandra embedded", e);
        throw new IllegalStateException("Timeout starting Cassandra embedded", e);
    }

    // Generate an OrderedShutdownHook to shutdown all connections from java clients before closing the server
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            log.info("Calling stop on Embedded Cassandra server");
            daemonRef.get().stop();

            log.info("Calling shutdown on all Cluster instances");
            // First call shutdown on all registered Java driver Cluster instances
            orderedShutdownHook.callShutDown();

            log.info("Shutting down embedded Cassandra server");
            // Then shutdown the server
            executor.shutdownNow();
        }
    });
}