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

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

Introduction

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

Prototype

public final void set(V newValue) 

Source Link

Document

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

Usage

From source file:org.commonjava.indy.promote.data.PromotionManager.java

private PathsPromoteResult doRollbackPathsPromote(PathsPromoteResult result) throws IndyWorkflowException {
    StoreKey targetKey = result.getRequest().getTarget();

    final List<Transfer> contents = getTransfersForPaths(targetKey, result.getCompletedPaths());
    final Set<String> completed = result.getCompletedPaths();
    final Set<String> skipped = result.getSkippedPaths();

    if (completed == null || completed.isEmpty()) {
        result.setError(null);/*from  w w w .j  a  va 2s.  c  o  m*/
        return result;
    }

    Set<String> pending = result.getPendingPaths() == null ? new HashSet<>()
            : new HashSet<>(result.getPendingPaths());

    final AtomicReference<String> error = new AtomicReference<>();
    final boolean copyToSource = result.getRequest().isPurgeSource();

    ArtifactStore source = null;
    try {
        source = storeManager.getArtifactStore(result.getRequest().getSource());
    } catch (final IndyDataException e) {
        String msg = String.format("Failed to retrieve artifact store: %s. Reason: %s",
                result.getRequest().getSource(), e.getMessage());

        logger.error(msg, e);
        error.set(msg);
    }

    AtomicReference<IndyWorkflowException> wfEx = new AtomicReference<>();
    if (error.get() == null) {
        ArtifactStore src = source;
        byPathTargetLocks.lockAnd(targetKey, config.getLockTimeoutSeconds(), k -> {
            for (final Transfer transfer : contents) {
                if (transfer != null && transfer.exists()) {
                    try {
                        if (copyToSource) {
                            final String path = transfer.getPath();
                            try (InputStream stream = transfer.openInputStream(true)) {
                                contentManager.store(src, path, stream, TransferOperation.UPLOAD,
                                        new EventMetadata());
                            } catch (IndyWorkflowException e) {
                                wfEx.set(e);
                                return null;
                            }
                        }

                        transfer.delete(true);
                        completed.remove(transfer.getPath());
                        pending.add(transfer.getPath());
                    } catch (final IOException e) {
                        String msg = String.format(
                                "Failed to rollback path promotion of: %s from: %s. Reason: %s", transfer,
                                result.getRequest().getSource(), e.getMessage());
                        logger.error(msg, e);
                        error.set(msg);
                    }
                }
            }

            return null;
        }, (k, lock) -> {
            String msg = String.format("Failed to acquire promotion lock on target: %s in %d seconds.",
                    targetKey, config.getLockTimeoutSeconds());
            logger.warn(msg);
            error.set(msg);

            return false;
        });

        IndyWorkflowException wfException = wfEx.get();
        if (wfException != null) {
            throw wfException;
        }

    }

    PathsPromoteResult ret = new PathsPromoteResult(result.getRequest(), pending, completed, skipped,
            error.get(), new ValidationResult());
    return ret.withPromotionId(result.getPromotionId());
}

From source file:org.apache.openejb.activemq.JMS2AMQTest.java

@Test
public void cdi() throws InterruptedException {
    final String text = TEXT + "3";

    final AtomicReference<Throwable> error = new AtomicReference<>();
    final CountDownLatch ready = new CountDownLatch(1);
    final CountDownLatch over = new CountDownLatch(1);
    new Thread() {
        {/*from w w w  .  ja  v  a  2 s .  c  om*/
            setName(JMS2AMQTest.class.getName() + ".cdi#receiver");
        }

        @Override
        public void run() {
            final ContextsService contextsService = WebBeansContext.currentInstance().getContextsService();
            contextsService.startContext(RequestScoped.class, null); // spec defines it for request scope an transaction scope
            try {
                ready.countDown();
                assertEquals(text, context.createConsumer(destination3).receiveBody(String.class,
                        TimeUnit.MINUTES.toMillis(1)));

                // ensure we dont do a NPE if there is nothing to read
                assertNull(context.createConsumer(destination3).receiveBody(String.class, 100));
            } catch (final Throwable t) {
                error.set(t);
            } finally {
                contextsService.endContext(RequestScoped.class, null);
                over.countDown();
            }
        }
    }.start();

    ready.await(1, TimeUnit.MINUTES);
    sleep(150); // just to ensure we called receive already

    // now send the message
    try (final JMSContext context = cf.createContext()) {
        context.createProducer().send(destination3, text);
    } catch (final JMSRuntimeException ex) {
        fail(ex.getMessage());
    }

    over.await(1, TimeUnit.MINUTES);

    // ensure we got the message and no exception
    final Throwable exception = error.get();
    if (exception != null) {
        exception.printStackTrace();
    }
    assertNull(exception == null ? "ok" : exception.getMessage(), exception);
}

From source file:org.jasig.ssp.service.impl.EvaluatedSuccessIndicatorServiceImpl.java

@Override
public List<EvaluatedSuccessIndicatorTO> getForPerson(final UUID personId, final ObjectStatus status)
        throws ObjectNotFoundException {

    // Elaborate transaction management workaround b/c we can't avoid opening a transaction, but any exception
    // that crosses a transactional boundary in the code will mark the transaction as rollback only, which is
    // fine except that if we just tag this method with @Transactional(readOnly=true), the transaction manager
    // will still attempt a commit if the exception doesn't exit all the way out of this method (which is
    // what we usually want in this specific case - we want to try to return as many indicators as we can). And
    // if you attempt to commit a transaction marked as rollback only, you get a
    // org.springframework.transaction.UnexpectedRollbackException
    TransactionTemplate transactionTemplate = new TransactionTemplate(platformTransactionManager);
    transactionTemplate.setReadOnly(true);
    final AtomicReference<List<EvaluatedSuccessIndicatorTO>> rsltHolder = new AtomicReference<>();
    final AtomicReference<ObjectNotFoundException> onfeHolder = new AtomicReference<>();
    try {//from ww w.  ja v  a2  s  .co m
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus txnStatus) {
                try {
                    getForPersonInTransaction(personId, status, rsltHolder);
                } catch (ObjectNotFoundException e) {
                    onfeHolder.set(e);
                    throw new RuntimeException("Rolling back transaction", e);
                }
            }
        });
    } catch (UnexpectedRollbackException e) {
        // nothing to be done, totally normal. see comments above.
    } catch (RuntimeException e) {
        if (onfeHolder.get() == null) {
            throw e;
        } // otherwise it's just us, rolling back the transaction, nothing to be done, totally normal
    }

    if (onfeHolder.get() != null) {
        throw onfeHolder.get();
    }

    return rsltHolder.get();
}

From source file:blusunrize.immersiveengineering.api.ApiUtils.java

public static Connection raytraceWires(World world, Vec3d start, Vec3d end, @Nullable Connection ignored) {
    Map<BlockPos, ImmersiveNetHandler.BlockWireInfo> inDim = ImmersiveNetHandler.INSTANCE.blockWireMap
            .lookup(world.provider.getDimension());
    AtomicReference<Connection> ret = new AtomicReference<>();
    AtomicDouble minDistSq = new AtomicDouble(Double.POSITIVE_INFINITY);
    if (inDim != null) {
        Utils.rayTrace(start, end, world, (pos) -> {
            if (inDim.containsKey(pos)) {
                ImmersiveNetHandler.BlockWireInfo info = inDim.get(pos);
                for (int i = 0; i < 2; i++) {
                    Set<Triple<Connection, Vec3d, Vec3d>> conns = i == 0 ? info.in : info.near;
                    for (Triple<Connection, Vec3d, Vec3d> conn : conns) {
                        Connection c = conn.getLeft();
                        if (ignored == null || !c.hasSameConnectors(ignored)) {
                            Vec3d startRelative = start.add(-pos.getX(), -pos.getY(), -pos.getZ());
                            Vec3d across = conn.getRight().subtract(conn.getMiddle());
                            double t = Utils.getCoeffForMinDistance(startRelative, conn.getMiddle(), across);
                            t = MathHelper.clamp(0, t, 1);
                            Vec3d closest = conn.getMiddle().add(t * across.x, t * across.y, t * across.z);
                            double distSq = closest.squareDistanceTo(startRelative);
                            if (distSq < minDistSq.get()) {
                                ret.set(c);
                                minDistSq.set(distSq);
                            }/*from  w w  w. jav  a2s .  c o  m*/
                        }
                    }
                }
            }
        });
    }

    return ret.get();
}

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);
        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()));
            }//  ww  w  . j a va  2  s.  co  m
        });
    }).<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:org.apache.hadoop.hdfs.server.blockmanagement.TestBlockReportRateLimiting.java

/**
 * Start a 2-node cluster with only one block report lease.  When the
 * first datanode gets a lease, kill it.  Then wait for the lease to
 * expire, and the second datanode to send a full block report.
 *//*from  w w w.j a v a2s. com*/
@Test(timeout = 180000)
public void testLeaseExpiration() throws Exception {
    Configuration conf = new Configuration();
    conf.setInt(DFS_NAMENODE_MAX_FULL_BLOCK_REPORT_LEASES, 1);
    conf.setLong(DFS_NAMENODE_FULL_BLOCK_REPORT_LEASE_LENGTH_MS, 100L);

    final Semaphore gotFbrSem = new Semaphore(0);
    final AtomicReference<String> failure = new AtomicReference<>();
    final AtomicReference<MiniDFSCluster> cluster = new AtomicReference<>();
    final AtomicReference<String> datanodeToStop = new AtomicReference<>();
    final BlockManagerFaultInjector injector = new BlockManagerFaultInjector() {

        @Override
        public void incomingBlockReportRpc(DatanodeID nodeID, BlockReportContext context) throws IOException {
            if (context.getLeaseId() == 0) {
                setFailure(failure,
                        "Got unexpected rate-limiting-" + "bypassing full block report RPC from " + nodeID);
            }
            if (nodeID.getXferAddr().equals(datanodeToStop.get())) {
                throw new IOException("Injecting failure into block " + "report RPC for " + nodeID);
            }
            gotFbrSem.release();
        }

        @Override
        public void requestBlockReportLease(DatanodeDescriptor node, long leaseId) {
            if (leaseId == 0) {
                return;
            }
            datanodeToStop.compareAndSet(null, node.getXferAddr());
        }

        @Override
        public void removeBlockReportLease(DatanodeDescriptor node, long leaseId) {
        }
    };
    try {
        BlockManagerFaultInjector.instance = injector;
        cluster.set(new MiniDFSCluster.Builder(conf).numDataNodes(2).build());
        cluster.get().waitActive();
        Assert.assertNotNull(cluster.get().stopDataNode(datanodeToStop.get()));
        gotFbrSem.acquire();
        Assert.assertNull(failure.get());
    } finally {
        if (cluster.get() != null) {
            cluster.get().shutdown();
        }
    }
}

From source file:hello.MetricsActivator.java

private MessageHandler handlerInAnonymousWrapper(final Object bean) {
    if (bean != null && bean.getClass().isAnonymousClass()) {
        final AtomicReference<MessageHandler> wrapped = new AtomicReference<MessageHandler>();
        ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {

            @Override//from  ww w  . j ava 2  s  . co  m
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                field.setAccessible(true);
                Object handler = field.get(bean);
                if (handler instanceof MessageHandler) {
                    wrapped.set((MessageHandler) handler);
                }
            }
        }, new FieldFilter() {

            @Override
            public boolean matches(Field field) {
                return wrapped.get() == null && field.getName().startsWith("val$");
            }
        });
        return wrapped.get();
    } else {
        return null;
    }
}

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

private MapValue removeInternal(String key, Optional<byte[]> value, Optional<MapValue> tombstone) {
    checkState(!closed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);//  w  w w  .  j a  v a  2s  . c  o m
    checkNotNull(value, ERROR_NULL_VALUE);
    tombstone.ifPresent(v -> checkState(v.isTombstone()));

    counter.incrementCount();
    AtomicBoolean updated = new AtomicBoolean(false);
    AtomicReference<MapValue> previousValue = new AtomicReference<>();
    items.compute(key, (k, existing) -> {
        boolean valueMatches = true;
        if (value.isPresent() && existing != null && existing.isAlive()) {
            valueMatches = Arrays.equals(value.get(), existing.get());
        }
        if (existing == null) {
            log.trace("ECMap Remove: Existing value for key {} is already null", k);
        }
        if (valueMatches) {
            if (existing == null) {
                updated.set(tombstone.isPresent());
            } else {
                updated.set(!tombstone.isPresent() || tombstone.get().isNewerThan(existing));
            }
        }
        if (updated.get()) {
            previousValue.set(existing);
            return tombstone.orElse(null);
        } else {
            return existing;
        }
    });
    return previousValue.get();
}

From source file:org.commonjava.indy.promote.data.PromotionManager.java

private ValidationResult doValidationAndPromote(GroupPromoteRequest request, AtomicReference<Exception> error,
        String user, String baseUrl) {
    ValidationResult validation = new ValidationResult();
    logger.info("Running validations for promotion of: {} to group: {}", request.getSource(),
            request.getTargetGroup());//from w  w  w  . j ava 2 s.  c om

    final StoreKey targetKey = getTargetKey(request.getTargetGroup());
    byGroupTargetLocks.lockAnd(targetKey, config.getLockTimeoutSeconds(), k -> {
        Group target;
        try {
            target = (Group) storeManager.getArtifactStore(request.getTargetKey());
        } catch (IndyDataException e) {
            error.set(new PromotionException("Cannot retrieve target group: %s. Reason: %s", e,
                    request.getTargetGroup(), e.getMessage()));
            return null;
        }

        try {
            ValidationRequest validationRequest = validator.validate(request, validation, baseUrl);

            if (validation.isValid()) {
                if (!request.isDryRun() && !target.getConstituents().contains(request.getSource())) {
                    // give the preUpdate event a different object to compare vs. the original group.
                    target = target.copyOf();
                    target.addConstituent(request.getSource());
                    try {
                        final ChangeSummary changeSummary = new ChangeSummary(user, "Promoting "
                                + request.getSource() + " into membership of group: " + target.getKey());

                        storeManager.storeArtifactStore(target, changeSummary, false, true,
                                new EventMetadata());
                        clearStoreNFC(validationRequest.getSourcePaths(), target);

                        if (hosted == request.getSource().getType() && config.isAutoLockHostedRepos()) {
                            HostedRepository source = (HostedRepository) storeManager
                                    .getArtifactStore(request.getSource());

                            source.setReadonly(true);

                            final ChangeSummary readOnlySummary = new ChangeSummary(user, "Promoting "
                                    + request.getSource() + " into membership of group: " + target.getKey());

                            storeManager.storeArtifactStore(source, readOnlySummary, false, true,
                                    new EventMetadata());
                        }
                    } catch (IndyDataException e) {
                        error.set(new PromotionException(
                                "Failed to store group: %s with additional member: %s. Reason: %s", e,
                                target.getKey(), request.getSource(), e.getMessage()));
                    }
                }
            }
        } catch (PromotionValidationException | IndyWorkflowException e) {
            error.set(e);
        }

        return null;
    }, (k, lock) -> {
        //FIXME: should we consider to repeat the promote process several times when lock failed?
        String errorMsg = String.format(
                "Failed to acquire group promotion lock on target when promote: %s in %d seconds.", targetKey,
                config.getLockTimeoutSeconds());
        logger.error(errorMsg);
        error.set(new PromotionException(errorMsg));

        return Boolean.FALSE;
    });

    return validation;
}

From source file:com.spotify.heroic.HeroicCore.java

/**
 * Start the Heroic core, step by step/*  w ww. ja  v a  2 s.c  o m*/
 * <p>
 * <p>
 * It sets up the early injector which is responsible for loading all the necessary components
 * to parse a configuration file.
 * <p>
 * <p>
 * Load all the external modules, which are configured in {@link #modules}.
 * <p>
 * <p>
 * Load and build the configuration using the early injector
 * <p>
 * <p>
 * Setup the primary injector which will provide the dependencies to the entire application
 * <p>
 * <p>
 * Run all bootstraps that are configured in {@link #late}
 * <p>
 * <p>
 * Start all the external modules. {@link #startLifeCycles}
 */
public HeroicCoreInstance newInstance() throws Exception {
    final CoreLoadingComponent loading = loadingInjector();

    loadModules(loading);

    final HeroicConfig config = config(loading);

    final CoreEarlyComponent early = earlyInjector(loading, config);
    runBootstrappers(early, this.early);

    // Initialize the instance injector with access to early components.
    final AtomicReference<CoreComponent> injector = new AtomicReference<>();

    final HeroicCoreInstance instance = new Instance(loading.async(), injector, early, config, this.late);

    final CoreComponent primary = primaryInjector(early, config, instance);

    primary.loadingLifeCycle().install();

    primary.internalLifeCycleRegistry().scoped("startup future").start(() -> {
        ((CoreHeroicContext) primary.context()).resolveCoreFuture();
        return primary.async().resolved(null);
    });

    // Update the instance injector, giving dynamic components initialized after this point
    // access to the primary
    // injector.
    injector.set(primary);

    return instance;
}