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.google.errorprone.bugpatterns.android.testdata.RestrictToEnforcerPositiveCases.java

void check() {

    // No bug - restrictto not enforced outside support lib
    CantUseRestrictToOutsideSupportLib var = null;

    // No bug - restrictto not enforced outside support lib
    cantUseRestrictToOutsideSupportLib();

    // BUG: Diagnostic contains: RestrictedMethodClass.doSomething() is restricted
    String string = (String) RestrictedMethodClass.doSomething();

    // BUG: Diagnostic contains: RestrictedClass.doSomething() is restricted
    String string2 = (String) RestrictedClass.doSomething();

    ExtendsExtendsRestricted obj = null;

    // BUG: Diagnostic contains: RestrictedAbstractMethod.restricted() is restricted
    obj.restricted();//from w ww.j a  v a  2  s  .  com

    // no bug - method is not restricted
    obj.interfaceMethod();

    // no bug - method is not restricted
    UnrestrictedSubclass.doSomething();

    // no bug - method is not restricted
    new UnrestrictedSubclass().instanceMethod();

    Runnable unrestricted = new UnrestrictedSubclass()::instanceMethod;

    // BUG: Diagnostic contains: RestrictedInterface is restricted
    ((RestrictedInterface) obj).toString();

    // BUG: Diagnostic contains: RestrictedInterface is restricted
    RestrictedInterface obj2 = obj;

    // BUG: Diagnostic contains: RestrictedInterface is restricted
    if (obj instanceof RestrictedInterface) {
    }

    // BUG: Diagnostic contains: RestrictedInterface.interfaceMethod() is restricted
    RestrictToEnforcerPositiveCasesApi.returnsRestrictedInterface().interfaceMethod();

    RestrictToEnforcerPositiveCasesApi.consumesRestrictedInterface(
            // BUG: Diagnostic contains: RestrictedInterface is restricted
            () -> {
                return;
            });

    // BUG: Diagnostic contains: RestrictedInterface is restricted
    RestrictToEnforcerPositiveCasesApi.consumesRestrictedInterface(System.out::println);

    // BUG: Diagnostic contains: RestrictedMethodClass.doSomething() is restricted
    Runnable runnable = RestrictedMethodClass::doSomething;

    // No bug - calling method on our own class
    new ExtendsUnrestrictedRestrictedInterfaceImplementor().interfaceMethod();

    // No bug - calling method on our own class
    Runnable runnable2 = new ExtendsUnrestrictedRestrictedInterfaceImplementor()::interfaceMethod;

    // BUG: Diagnostic contains: RestrictedOuterClass.UnrestrictedClass.doSomething() is restricted
    UnrestrictedClass.doSomething();

    new RestrictedAbstractMethod() {
        @Override
        // BUG: Diagnostic contains: RestrictedAbstractMethod.restricted() is restricted
        public void restricted() {
        }

        @Override
        public void interfaceMethod() {
        }
    };

    // BUG: Diagnostic contains: RestrictedClass is restricted
    AtomicReference<? extends RestrictedClass> ref = new AtomicReference<>(null);

    // BUG: Diagnostic contains: RestrictedClass.doSomething() is restricted
    ref.get().doSomething();

    // BUG: Diagnostic contains: RestrictedSubClass is restricted
    RestrictedSubClass subClass = null;

    // BUG: Diagnostic contains: RestrictedSubClass.superClassMethod() is restricted
    subClass.superClassMethod();

    // BUG: Diagnostic contains: RestrictedConstructor.RestrictedConstructor() is restricted
    new RestrictedConstructor();
}

From source file:jduagui.Controller.java

public static void getExtensions(String startPath, Map<String, Extension> exts) throws IOException {
    final AtomicReference<String> extension = new AtomicReference<>("");
    final File f = new File(startPath);
    final String str = "";
    Path path = Paths.get(startPath);

    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override//from  w w  w.j  a  va  2 s  .c o m
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            storageCache.put(file.toAbsolutePath().toString(), attrs.size());
            extension.set(FilenameUtils.getExtension(file.toAbsolutePath().toString()));

            if (extension.get().equals(str)) {
                if (exts.containsKey(noExt)) {
                    exts.get(noExt).countIncrement();
                    exts.get(noExt).increaseSize(attrs.size());
                } else {
                    exts.put(noExt, new Extension(new AtomicLong(1), new AtomicLong(attrs.size())));
                }
            } else {

                if (exts.containsKey(extension.get())) {
                    exts.get(extension.get()).countIncrement();
                    exts.get(extension.get()).increaseSize(attrs.size());
                } else {
                    exts.put(extension.get(), new Extension(new AtomicLong(1), new AtomicLong(attrs.size())));
                }
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }
    });
}

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  w  w  . j  av  a2 s . co 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.nextgis.maplibui.mapui.LayerFactoryUI.java

@Override
public void createNewLocalTMSLayer(final Context context, final LayerGroup groupLayer, final Uri uri) {
    String ext = "zip";
    String layerName = FileUtil.getFileNameByUri(context, uri, context.getString(R.string.new_layer));
    final int lastPeriodPos = layerName.lastIndexOf('.');
    if (lastPeriodPos > 0) {
        ext = layerName.substring(lastPeriodPos).toLowerCase();
        layerName = layerName.substring(0, lastPeriodPos);
    }/*from  w  ww.j a v a  2  s.  com*/
    if (context instanceof NGActivity) {
        NGActivity fragmentActivity = (NGActivity) context;

        if (ext.equals(".ngrc")) {
            Intent intent = new Intent(context, LayerFillService.class);
            intent.setAction(LayerFillService.ACTION_ADD_TASK);
            intent.putExtra(LayerFillService.KEY_URI, uri);
            intent.putExtra(LayerFillService.KEY_INPUT_TYPE, LayerFillService.TMS_LAYER);
            intent.putExtra(LayerFillService.KEY_LAYER_GROUP_ID, groupLayer.getId());

            LayerFillProgressDialogFragment.startFill(intent);
            return;
        }

        AtomicReference<Uri> temp = new AtomicReference<>(uri);
        if (MapUtil.isZippedGeoJSON(context, temp)) {
            createNewVectorLayer(context, groupLayer, temp.get());
            return;
        }

        CreateLocalLayerDialog newFragment = new CreateLocalLayerDialog();
        newFragment.setLayerGroup(groupLayer).setLayerType(LayerFillService.TMS_LAYER).setUri(uri)
                .setLayerName(layerName).setTitle(context.getString(R.string.create_tms_layer))
                .setTheme(fragmentActivity.getThemeId())
                .show(fragmentActivity.getSupportFragmentManager(), "create_tms_layer");
    }
}

From source file:com.dgtlrepublic.anitomyj.KeywordManager.java

/**
 * Finds a particular {@code keyword}. If found sets {@code category} and {@code options} to the found search
 * result./*  ww w  . java 2  s .c  o  m*/
 *
 * @param keyword  the keyword to search for
 * @param category an atomic reference that will be set/changed to the found keyword category
 * @param options  an atomic reference that will be set/changed to the found keyword options
 * @return true if the keyword was found; false otherwise
 */
public boolean findAndSet(String keyword, AtomicReference<ElementCategory> category,
        AtomicReference<KeywordOptions> options) {
    Map<String, Keyword> keys = getKeywordContainer(category.get());
    Keyword foundEntry = keys.get(keyword);
    if (foundEntry != null) {
        if (category.get() == kElementUnknown) {
            category.set(foundEntry.getCategory());
        } else if (foundEntry.getCategory() != category.get()) {
            return false;
        }

        options.set(foundEntry.getOptions());
        return true;
    }

    return false;
}

From source file:de.acosix.alfresco.utility.repo.subsystems.SubsystemChildApplicationContextManager.java

/**
 * Determines the instance ID for a specific child application context from within all the child application contexts managed by this
 * instance.//from   w  w w .  j  a  v  a  2  s . c om
 *
 * @param childApplicationContext
 *            the child application context
 * @return the ID of the child application instance or {@code null} if none of the currently active child application contexts match the
 *         provided one
 */
public String determineInstanceId(final ApplicationContext childApplicationContext) {
    this.lock.readLock().lock();
    try {
        final SubsystemApplicationContextManagerState state = (SubsystemApplicationContextManagerState) this
                .getState(false);

        final Collection<String> instanceIds = state.getInstanceIds();
        final AtomicReference<String> matchingInstanceId = new AtomicReference<>(null);

        for (final String id : instanceIds) {
            if (matchingInstanceId.get() == null) {
                final SubsystemChildApplicationContextFactory applicationContextFactory = state
                        .getApplicationContextFactory(id);
                final ApplicationContext readOnlyApplicationContext = applicationContextFactory
                        .getReadOnlyApplicationContext();

                if (readOnlyApplicationContext == childApplicationContext) {
                    matchingInstanceId.set(id);
                }
            }
        }

        return matchingInstanceId.get();
    } finally

    {
        this.lock.readLock().unlock();
    }
}

From source file:com.bfd.harpc.monitor.RpcMonitor.java

/**
 * ?/*from   w  w w. j  ava  2  s.  co  m*/
 * <p>
 * 
 * @param info
 * @param reference
 */
private void updateStatistics(StatisticsInfo info, AtomicReference<StatisticsInfo> reference) {
    StatisticsInfo current;
    StatisticsInfo update = new StatisticsInfo();
    do {
        current = reference.get();
        if (current == null) {
            update.setSuccess(info.getSuccess());
            update.setFailure(info.getFailure());
            update.setMaxtime(info.getMaxtime());
            update.setMintime(info.getMintime());
            update.setAvgtime(info.getAvgtime());
        } else {
            update.setSuccess(current.getSuccess() + info.getSuccess());
            update.setFailure(current.getFailure() + info.getFailure());
            update.setMaxtime(
                    current.getMaxtime() > info.getMaxtime() ? current.getMaxtime() : info.getMaxtime());
            update.setMintime(
                    current.getMintime() < info.getMintime() ? current.getMintime() : info.getMintime());
            update.setAvgtime(
                    (current.getAvgtime() * (update.getSuccess() + update.getFailure()) + info.getAvgtime())
                            / (update.getSuccess() + update.getFailure() + 1));
        }
    } while (!reference.compareAndSet(current, update));
}

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.//from  w  w  w .  ja  v  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();
}