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:com.google.dart.engine.internal.index.AbstractDartTest.java

/**
 * @return {@link ASTNode} which has required offset and type.
 *///w  ww.j a  va 2 s.c  o  m
public static <E extends ASTNode> E findNode(ASTNode root, final int offset, final Class<E> clazz) {
    final AtomicReference<E> resultRef = new AtomicReference<E>();
    root.accept(new GeneralizingASTVisitor<Void>() {
        @Override
        @SuppressWarnings("unchecked")
        public Void visitNode(ASTNode node) {
            if (node.getOffset() <= offset && offset < node.getEnd() && clazz.isInstance(node)) {
                resultRef.set((E) node);
            }
            return super.visitNode(node);
        }
    });
    E result = resultRef.get();
    assertNotNull(result);
    return result;
}

From source file:com.scvngr.levelup.core.test.TestThreadingUtils.java

/**
 * Validates that a fragment is either not managed by the fragment manager or is not visible to
 * the user.// ww  w.  j a  v a  2 s. c om
 *
 * @param <V> the type of Fragment.
 * @param instrumentation the test {@link Instrumentation}.
 * @param activity the activity for the test being run (null will fail validation).
 * @param fragmentManager the fragment manager the fragment was added to (null will fail
 *        validation).
 * @param tag the tag to check for (null will fail validation).
 * @return the Fragment that is not visible to the user.
 */
@NonNull
@SuppressWarnings("unchecked")
public static <V extends Fragment> V validateFragmentIsNotVisible(
        @NonNull final Instrumentation instrumentation, final Activity activity,
        final FragmentManager fragmentManager, final String tag) {
    AndroidTestCase.assertNotNull(tag);
    AndroidTestCase.assertNotNull(activity);
    AndroidTestCase.assertNotNull(fragmentManager);

    final AtomicReference<Fragment> reference = new AtomicReference<Fragment>();
    final LatchRunnable latchRunnable = new LatchRunnable() {
        @Override
        public void run() {
            final Fragment fragment = fragmentManager.findFragmentByTag(tag);

            if (null == fragment || !fragment.isVisible()) {
                reference.set(fragment);
                countDown();
            }
        }
    };

    AndroidTestCase.assertTrue(String.format(Locale.US, "%s is not visible", tag),
            waitForAction(instrumentation, activity, latchRunnable, true));

    return (V) reference.get();
}

From source file:com.scvngr.levelup.core.test.TestThreadingUtils.java

/**
 * Validates that a fragment is visible to the user.
 *
 * @param <V> the type of Fragment.
 * @param instrumentation the test {@link Instrumentation}.
 * @param activity the activity for the test being run (null will fail validation).
 * @param fragmentManager the fragment manager the fragment was added to (null will fail
 *        validation)./*from   ww w .j av a2 s.c  om*/
 * @param tag the tag to check for (null will fail validation).
 * @return the Fragment that is visible to the user.
 */
@NonNull
@SuppressWarnings("unchecked")
public static <V extends Fragment> V validateFragmentIsVisible(@NonNull final Instrumentation instrumentation,
        final Activity activity, final FragmentManager fragmentManager, final String tag) {
    AndroidTestCase.assertNotNull(tag);
    AndroidTestCase.assertNotNull(activity);
    AndroidTestCase.assertNotNull(fragmentManager);

    final AtomicReference<Fragment> reference = new AtomicReference<Fragment>();
    final LatchRunnable latchRunnable = new LatchRunnable() {
        @Override
        public void run() {
            final Fragment fragment = fragmentManager.findFragmentByTag(tag);

            if (null != fragment) {
                if (fragment.isVisible()) {
                    reference.set(fragment);
                    countDown();
                }
            }
        }
    };

    AndroidTestCase.assertTrue(String.format(Locale.US, "%s is visible", tag),
            waitForAction(instrumentation, activity, latchRunnable, true));

    return (V) reference.get();
}

From source file:io.lettuce.core.support.ConnectionPoolSupport.java

/**
 * Creates a new {@link GenericObjectPool} using the {@link Supplier}.
 *
 * @param connectionSupplier must not be {@literal null}.
 * @param config must not be {@literal null}.
 * @param wrapConnections {@literal false} to return direct connections that need to be returned to the pool using
 *        {@link ObjectPool#returnObject(Object)}. {@literal true} to return wrapped connection that are returned to the
 *        pool when invoking {@link StatefulConnection#close()}.
 * @param <T> connection type.// w ww .j  a v a  2s .  c  om
 * @return the connection pool.
 */
@SuppressWarnings("unchecked")
public static <T extends StatefulConnection<?, ?>> GenericObjectPool<T> createGenericObjectPool(
        Supplier<T> connectionSupplier, GenericObjectPoolConfig config, boolean wrapConnections) {

    LettuceAssert.notNull(connectionSupplier, "Connection supplier must not be null");
    LettuceAssert.notNull(config, "GenericObjectPoolConfig must not be null");

    AtomicReference<Origin<T>> poolRef = new AtomicReference<>();

    GenericObjectPool<T> pool = new GenericObjectPool<T>(new RedisPooledObjectFactory<T>(connectionSupplier),
            config) {

        @Override
        public T borrowObject() throws Exception {
            return wrapConnections ? ConnectionWrapping.wrapConnection(super.borrowObject(), poolRef.get())
                    : super.borrowObject();
        }

        @Override
        public void returnObject(T obj) {

            if (wrapConnections && obj instanceof HasTargetConnection) {
                super.returnObject((T) ((HasTargetConnection) obj).getTargetConnection());
                return;
            }
            super.returnObject(obj);
        }
    };

    poolRef.set(new ObjectPoolWrapper<>(pool));

    return pool;
}

From source file:org.eclipse.wb.tests.designer.core.model.parser.AbstractJavaInfoRelatedTest.java

/**
 * @return the {@link JavaInfo} which has variable with given name.
 *//*from ww  w.  j  a  v  a 2s  .c om*/
public static <T extends JavaInfo> T getJavaInfoByName(final String name) throws Exception {
    final AtomicReference<T> result = new AtomicReference<T>();
    EditorState.getActiveJavaInfo().accept0(new ObjectInfoVisitor() {
        @Override
        @SuppressWarnings("unchecked")
        public void endVisit(ObjectInfo objectInfo) throws Exception {
            if (result.get() != null) {
                return;
            }
            if (objectInfo instanceof JavaInfo) {
                JavaInfo javaInfo = (JavaInfo) objectInfo;
                if (isRequestedJavaInfo(javaInfo)) {
                    result.set((T) javaInfo);
                }
            }
        }

        private boolean isRequestedJavaInfo(JavaInfo javaInfo) throws Exception {
            VariableSupport variable = javaInfo.getVariableSupport();
            // check name
            if (variable.hasName() && name.equals(variable.getName())) {
                return true;
            }
            // check title
            try {
                if (name.equals(variable.getTitle())) {
                    return true;
                }
            } catch (Throwable e) {
            }
            // no
            return false;
        }
    });
    return result.get();
}

From source file:io.lettuce.core.support.ConnectionPoolSupport.java

/**
 * Creates a new {@link SoftReferenceObjectPool} using the {@link Supplier}.
 *
 * @param connectionSupplier must not be {@literal null}.
 * @param wrapConnections {@literal false} to return direct connections that need to be returned to the pool using
 *        {@link ObjectPool#returnObject(Object)}. {@literal true} to return wrapped connection that are returned to the
 *        pool when invoking {@link StatefulConnection#close()}.
 * @param <T> connection type.//from   w  w  w . jav  a 2s  .c  o m
 * @return the connection pool.
 */
@SuppressWarnings("unchecked")
public static <T extends StatefulConnection<?, ?>> SoftReferenceObjectPool<T> createSoftReferenceObjectPool(
        Supplier<T> connectionSupplier, boolean wrapConnections) {

    LettuceAssert.notNull(connectionSupplier, "Connection supplier must not be null");

    AtomicReference<Origin<T>> poolRef = new AtomicReference<>();

    SoftReferenceObjectPool<T> pool = new SoftReferenceObjectPool<T>(
            new RedisPooledObjectFactory<>(connectionSupplier)) {
        @Override
        public T borrowObject() throws Exception {
            return wrapConnections ? ConnectionWrapping.wrapConnection(super.borrowObject(), poolRef.get())
                    : super.borrowObject();
        }

        @Override
        public void returnObject(T obj) throws Exception {

            if (wrapConnections && obj instanceof HasTargetConnection) {
                super.returnObject((T) ((HasTargetConnection) obj).getTargetConnection());
                return;
            }
            super.returnObject(obj);
        }
    };
    poolRef.set(new ObjectPoolWrapper<>(pool));

    return pool;
}

From source file:com.scvngr.levelup.core.test.TestThreadingUtils.java

/**
 * Validates that a fragment was added successfully and validates the ID of the container it was
 * added to.//www  .j av a 2  s . c o m
 *
 * @param <V> the type of Fragment.
 * @param instrumentation the test {@link Instrumentation}.
 * @param activity the activity for the test being run (null will fail validation).
 * @param fragmentManager the fragment manager the fragment was added to (null will fail
 *        validation).
 * @param tag the tag to check for (null will fail validation).
 * @param parentId the id of the parent container the fragment is expected to be in or pass
 *        {@link #PARENT_ID_UNDEFINED} if no parent id should be validated.
 * @return the Fragment that is added.
 */
@NonNull
@SuppressWarnings("unchecked")
public static <V extends Fragment> V validateFragmentAdded(@NonNull final Instrumentation instrumentation,
        final Activity activity, final FragmentManager fragmentManager, final String tag, final int parentId) {
    AndroidTestCase.assertNotNull(tag);
    AndroidTestCase.assertNotNull(activity);
    AndroidTestCase.assertNotNull(fragmentManager);

    final AtomicReference<Fragment> reference = new AtomicReference<Fragment>();
    final LatchRunnable latchRunnable = new LatchRunnable() {
        @Override
        public void run() {
            final Fragment fragment = fragmentManager.findFragmentByTag(tag);

            if (null != fragment) {
                if (fragment.isAdded()) {
                    if (PARENT_ID_UNDEFINED != parentId) {
                        final View parent = (View) fragment.getView().getParent();
                        AndroidTestCase.assertEquals("In the proper container", parentId, parent.getId());
                    }

                    reference.set(fragment);
                    countDown();
                }
            }
        }
    };

    AndroidTestCase.assertTrue(String.format(Locale.US, "%s added", tag),
            waitForAction(instrumentation, NullUtils.nonNullContract(activity), latchRunnable, true));

    return (V) reference.get();
}

From source file:com.splout.db.common.TestUtils.java

/**
 * Returns a DNode instance if, after a maximum of X trials, we can find a port to bind it to.
 * The configuration passed by instance might have been modified accordingly.
 *//*from w ww .  j av a  2 s. c  o  m*/
public static DNode getTestDNode(final SploutConfiguration testConfig, final IDNodeHandler handler,
        final String dataFolder, boolean deleteDataFolder) throws Throwable {
    final AtomicReference<DNode> reference = new AtomicReference<DNode>();
    testConfig.setProperty(DNodeProperties.DATA_FOLDER, dataFolder);
    if (deleteDataFolder) {
        File file = new File(dataFolder);
        if (file.exists()) {
            FileUtils.deleteDirectory(file);
        }
        file.mkdir();
    }
    testConfig.setProperty(FetcherProperties.TEMP_DIR, "fetcher-" + dataFolder);
    File fetcherTmp = new File("fetcher-" + dataFolder);
    if (fetcherTmp.exists()) {
        FileUtils.deleteDirectory(fetcherTmp);
    }
    fetcherTmp.mkdir();
    CatchAndRetry dNodeInit = new CatchAndRetry(TTransportException.class, 50) {

        @Override
        public void businessLogic() throws Throwable {
            DNode dNode = new DNode(testConfig, handler);
            dNode.init();
            reference.set(dNode);
        }

        @Override
        public void retryLogic() {
            testConfig.setProperty(DNodeProperties.PORT, testConfig.getInt(DNodeProperties.PORT) + 1);
        }
    };
    dNodeInit.catchAndRetry();
    return reference.get();
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.index.DefaultCompoundValueResolver.java

@Override
public String resolve(Object value, JsonObject root, String id, String fieldName, RedissonIndex index) {
    AtomicReference<String> s = new AtomicReference<>();
    if (StringUtils.isBlank(index.valueField())) {
        s.set(value instanceof String ? (String) value : Json.encode(value));
    } else {/*from   ww w.java 2 s . co m*/
        s.set(root.getString(index.valueField()));
    }
    Arrays.stream(index.compoundIndexFields()).forEach(
            e -> s.set(s.get().concat(RedisRepository.DEFAULT_SEPERATOR).concat(root.getValue(e).toString())));
    return s.get().concat(RedisRepository.DEFAULT_SEPERATOR).concat(id);
}

From source file:com.lambdaworks.redis.support.ConnectionPoolSupport.java

/**
 * Creates a new {@link GenericObjectPool} using the {@link Supplier}.
 *
 * @param connectionSupplier must not be {@literal null}.
 * @param config must not be {@literal null}.
 * @param wrapConnections {@literal false} to return direct connections that need to be returned to the pool using
 *        {@link ObjectPool#returnObject(Object)}. {@literal true} to return wrapped connection that are returned to the
 *        pool when invoking {@link StatefulConnection#close()}.
 * @param <T> connection type.//from  w  w  w  .  ja va  2  s .  c om
 * @return the connection pool.
 */
@SuppressWarnings("unchecked")
public static <T extends StatefulConnection<?, ?>> GenericObjectPool<T> createGenericObjectPool(
        Supplier<T> connectionSupplier, GenericObjectPoolConfig config, boolean wrapConnections) {

    LettuceAssert.notNull(connectionSupplier, "Connection supplier must not be null");
    LettuceAssert.notNull(config, "GenericObjectPoolConfig must not be null");

    AtomicReference<ObjectPool<T>> poolRef = new AtomicReference<>();

    GenericObjectPool<T> pool = new GenericObjectPool<T>(new RedisPooledObjectFactory<>(connectionSupplier),
            config) {

        @Override
        public synchronized T borrowObject() throws Exception {
            return wrapConnections ? wrapConnection(super.borrowObject(), this) : super.borrowObject();
        }

        @Override
        public synchronized void returnObject(T obj) {

            if (wrapConnections && obj instanceof HasTargetConnection) {
                super.returnObject((T) ((HasTargetConnection) obj).getTargetConnection());
                return;
            }
            super.returnObject(obj);
        }
    };

    poolRef.set(pool);

    return pool;
}