Java Code Examples for java.util.concurrent.atomic.AtomicInteger#getAndSet()

The following examples show how to use java.util.concurrent.atomic.AtomicInteger#getAndSet() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: JerryMouse   File: FileScannerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testFileScan() throws Exception {
    File file = new File("build");
    FileScanner fileScanner = new FileScanner(file,10);
    AtomicInteger counter = new AtomicInteger();
    counter.getAndSet(0);
    Listener listener = event -> counter.getAndIncrement();
    fileScanner.registerListener(listener);
    Thread f = new Thread(fileScanner);
    f.start();
    TimeUnit.MILLISECONDS.sleep(50);
    FileWriter myWriter = new FileWriter("build/test.txt");
    myWriter.write("test");
    myWriter.close();
    TimeUnit.MILLISECONDS.sleep(50);
    FileUtils.deleteDir(new File("build/test.txt"));
    TimeUnit.MILLISECONDS.sleep(50);
    assertEquals(2,counter.get());
}
 
Example 2
Source Project: rome   File: AtomicIntegerDemo.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    int temValue = 0;
    AtomicInteger value = new AtomicInteger(0);
    temValue = value.getAndSet(3);
    // 首先get,获取到当前value的值为0,并赋值给temValue,之后设置新值3,此时value为3
    System.out.println("temValue = " + temValue + " value = " + value);

    temValue = value.getAndIncrement();
    System.out.println("temValue = " + temValue + " value = " + value);

    temValue = value.getAndDecrement();
    System.out.println("temValue = " + temValue + " value = " + value);

    temValue = value.getAndAdd(10);
    System.out.println("temValue = " + temValue + " value = " + value);
}
 
Example 3
public static <T> T invoke(Callable<T> method, DomainNames domain) throws Exception {
    if (!initialized) {
        throw new IllegalStateException("RetryPolicyAdapter should be initialized before invoking api calls");
    }
    AtomicInteger retryCountForDomain = getRetryCountForDomain(domain);
    while (retryCountForDomain.get() < DEFAULT_MAX_RETRIES) {
        try {
            sleepIfLimitIsExceeded(domain);
            T result = method.call();
            retryCountForDomain.getAndSet(0);
            return result;
        } catch (ApiException e) {
            if (isRateLimited(e) || isInternalServerError(e)) {
                sleepAndIncrementCounter(domain);
                logger.info("Retrying, # of retries: " + retryCountForDomain + "  error code:" + e.getCode());
            } else {
                throw e;
            }
        }
    }
    throw new Exception("Max number of api call tries exceeded");
}
 
Example 4
Source Project: geoar-app   File: Texture.java    License: Apache License 2.0 6 votes vote down vote up
private static AtomicInteger createTextureHandle() {
	int newHandle = -1;
	if (HANDLE_CACHE.size() >= MAX_TEXTURES) {
		AtomicInteger reusedHandle = HANDLE_CACHE.poll();
		newHandle = reusedHandle.getAndSet(-1);
	}

	if (newHandle == -1) {
		int[] textures = new int[1];
		GLES20.glGenTextures(1, textures, 0);
		newHandle = textures[0];
	}
	AtomicInteger result = new AtomicInteger(newHandle);
	HANDLE_CACHE.add(result);

	return result;
}
 
Example 5
@Test
public void forwardsCalls() {
  AutoConfiguredLoadBalancer lb =
      (AutoConfiguredLoadBalancer) lbf.newLoadBalancer(new TestHelper());

  final AtomicInteger calls = new AtomicInteger();
  TestLoadBalancer testlb = new TestLoadBalancer() {

    @Override
    public void handleNameResolutionError(Status error) {
      calls.getAndSet(1);
    }

    @Override
    public void handleSubchannelState(Subchannel subchannel, ConnectivityStateInfo stateInfo) {
      calls.getAndSet(2);
    }

    @Override
    public void shutdown() {
      calls.getAndSet(3);
    }
  };

  lb.setDelegate(testlb);

  lb.handleNameResolutionError(Status.RESOURCE_EXHAUSTED);
  assertThat(calls.getAndSet(0)).isEqualTo(1);

  lb.handleSubchannelState(null, null);
  assertThat(calls.getAndSet(0)).isEqualTo(2);

  lb.shutdown();
  assertThat(calls.getAndSet(0)).isEqualTo(3);
}
 
Example 6
/**
 * Updates the number of threads that can be simultaneously used for
 * executing processors.
 *
 * @param maxThreadCount This method must be called while holding the write
 * lock!
 */
private void setMaxThreadCount(final int maxThreadCount, final FlowEngine engine, final AtomicInteger maxThreads) {
    if (maxThreadCount < 1) {
        throw new IllegalArgumentException();
    }

    maxThreads.getAndSet(maxThreadCount);
    if (null != engine && engine.getCorePoolSize() < maxThreadCount) {
        engine.setCorePoolSize(maxThreads.intValue());
    }
}
 
Example 7
@Test
public void testClear() {
    AsyncLoadingCache<String, Integer> cachedResult = new AsyncLoadingCache<>(30000);
    AtomicInteger value = new AtomicInteger(111);
    Supplier<CompletableFuture<Integer>> supplier = () -> CompletableFuture.supplyAsync(value::get);

    consistently("we get the original value", () -> cachedResult.orElseGet("a-key", supplier).join(), is(111), 10, 2);
    value.getAndSet(222);
    consistently("we still see the cached value", () -> cachedResult.orElseGet("a-key", supplier).join(), is(111), 10, 2);
    cachedResult.clear();
    consistently("we see the new value", () -> cachedResult.orElseGet("a-key", supplier).join(), is(222), 10, 2);
}
 
Example 8
Source Project: phoebus   File: SpamDemo.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception
    {
        // * base-7.0.2.2
        //   pipeline= 2 (ack every 1):    OK, > 60000 updates/sec
        //   pipeline= 4 (ack every 2):    OK, >100000 updates/sec
        //   pipeline=10 (ack every 5):    Stops after 4 updates
        int pipeline = 4;
        if (args.length == 1)
            pipeline = Integer.parseInt(args[0]);

        final PVAClient pva = new PVAClient();
        final PVAChannel channel = pva.getChannel("spam");
        channel.connect().get(5, TimeUnit.SECONDS);

        AtomicInteger updates = new AtomicInteger();
        final AutoCloseable subscription = channel.subscribe("", pipeline, (ch, changes, overruns, data) ->
        {
            updates.incrementAndGet();
            // System.out.println(data);
        });

        while (true)
        {
            TimeUnit.SECONDS.sleep(10);
            final int got = updates.getAndSet(0);
            System.err.println("pipeline=" + pipeline + " got " + got + " updates in 10 seconds, " + got/10 + " per sec");
        }

//        subscription.close();
//        channel.close();
//        pva.close();
    }
 
Example 9
private static void sleepIfLimitIsExceeded(DomainNames domain) throws InterruptedException {
    AtomicInteger apiCallCount = getCounterForDomain(domain);
    if ((apiCallCount.get()) >= (getLimitForDomain(domain))) {
        long current = System.currentTimeMillis();
        int sleepTime = 60000 - (int) (current - startTime);
        startTime = current;
        apiCallCount.getAndSet(0);
        logger.warn("thread will sleep for :" + sleepTime + " milliseconds.");
        Thread.sleep(sleepTime);
    }
}
 
Example 10
@SuppressWarnings("deprecation")
@Test
public void forwardsCalls() {
  AutoConfiguredLoadBalancer lb = lbf.newLoadBalancer(new TestHelper());

  final AtomicInteger calls = new AtomicInteger();
  TestLoadBalancer testlb = new TestLoadBalancer() {

    @Override
    public void handleNameResolutionError(Status error) {
      calls.getAndSet(1);
    }

    @Override
    public void handleSubchannelState(Subchannel subchannel, ConnectivityStateInfo stateInfo) {
      calls.getAndSet(2);
    }

    @Override
    public void shutdown() {
      calls.getAndSet(3);
    }
  };

  lb.setDelegate(testlb);

  lb.handleNameResolutionError(Status.RESOURCE_EXHAUSTED);
  assertThat(calls.getAndSet(0)).isEqualTo(1);

  lb.handleSubchannelState(null, null);
  assertThat(calls.getAndSet(0)).isEqualTo(2);

  lb.shutdown();
  assertThat(calls.getAndSet(0)).isEqualTo(3);
}
 
Example 11
Source Project: nifi   File: FlowController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Updates the number of threads that can be simultaneously used for executing processors.
 * This method must be called while holding the write lock!
 *
 * @param maxThreadCount max number of threads
 */
private void setMaxThreadCount(final int maxThreadCount, final FlowEngine engine, final AtomicInteger maxThreads) {
    if (maxThreadCount < 1) {
        throw new IllegalArgumentException("Cannot set max number of threads to less than 2");
    }

    maxThreads.getAndSet(maxThreadCount);
    if (null != engine && engine.getCorePoolSize() < maxThreadCount) {
        engine.setCorePoolSize(maxThreads.intValue());
    }
}
 
Example 12
Source Project: aparapi   File: Kernel.java    License: Apache License 2.0 4 votes vote down vote up
@OpenCLMapping(atomic32 = true, mapTo = "atomic_xchg")
protected final int atomicXchg(AtomicInteger p, int newVal) {
 return p.getAndSet(newVal);
}