Java Code Examples for java.util.concurrent.atomic.AtomicLong.set()

The following are Jave code examples for showing how to use set() of the java.util.concurrent.atomic.AtomicLong class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: elasticsearch_my   File: BootstrapCheckTests.java   View Source Code Vote up 6 votes
public void testMaxMapCountCheck() throws NodeValidationException {
    final int limit = 1 << 18;
    final AtomicLong maxMapCount = new AtomicLong(randomIntBetween(1, limit - 1));
    final BootstrapChecks.MaxMapCountCheck check = new BootstrapChecks.MaxMapCountCheck() {
        @Override
        long getMaxMapCount() {
            return maxMapCount.get();
        }
    };

    final NodeValidationException e = expectThrows(
            NodeValidationException.class,
            () -> BootstrapChecks.check(true, Collections.singletonList(check), "testMaxMapCountCheck"));
    assertThat(e.getMessage(), containsString("max virtual memory areas vm.max_map_count"));

    maxMapCount.set(randomIntBetween(limit + 1, Integer.MAX_VALUE));

    BootstrapChecks.check(true, Collections.singletonList(check), "testMaxMapCountCheck");

    // nothing should happen if current vm.max_map_count is not
    // available
    maxMapCount.set(-1);
    BootstrapChecks.check(true, Collections.singletonList(check), "testMaxMapCountCheck");
}
 
Example 2
Project: incubator-netbeans   File: Stamps.java   View Source Code Vote up 6 votes
private static void discardCachesImpl(AtomicLong al) {
    File user = Places.getUserDirectory();
    long now = System.currentTimeMillis();
    if (user != null) {
        File f = new File(user, ".lastModified");
        if (f.exists()) {
            f.setLastModified(now);
        } else {
            f.getParentFile().mkdirs();
            try {
                f.createNewFile();
            } catch (IOException ex) {
                LOG.log(Level.WARNING, "Cannot create " + f, ex);
            }
        }
    }
    if (al != null) {
        al.set(now);
    }
}
 
Example 3
Project: incubator-netbeans   File: Stamps.java   View Source Code Vote up 6 votes
private static boolean highestStampForDir(File file, AtomicReference<File> newestFile, AtomicLong result, AtomicInteger crc) {
    if (file.getName().equals(".nbattrs")) { // NOI18N
        return true;
    }

    File[] children = file.listFiles();
    if (children == null) {
        if (crc != null) {
            crc.addAndGet(file.getName().length());
        }
        long time = file.lastModified();
        if (time > result.longValue()) {
            newestFile.set(file);
            result.set(time);
        }
        return false;
    }
    
    for (File f : children) {
        highestStampForDir(f, newestFile, result, crc);
    }
    return true;
}
 
Example 4
Project: https-github.com-apache-zookeeper   File: CreateTTLTest.java   View Source Code Vote up 6 votes
@Test
public void testModifying()
        throws IOException, KeeperException, InterruptedException {
    Stat stat = new Stat();
    zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, stat, 100);
    Assert.assertEquals(0, stat.getEphemeralOwner());

    final AtomicLong fakeElapsed = new AtomicLong(0);
    ContainerManager containerManager = newContainerManager(fakeElapsed);
    containerManager.checkContainers();
    Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));

    for ( int i = 0; i < 10; ++i ) {
        fakeElapsed.set(50);
        zk.setData("/foo", new byte[i + 1], -1);
        containerManager.checkContainers();
        Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
    }

    fakeElapsed.set(200);
    containerManager.checkContainers();
    Assert.assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
}
 
Example 5
Project: elasticsearch_my   File: CacheTests.java   View Source Code Vote up 5 votes
public void testPromotion() {
    AtomicLong now = new AtomicLong();
    Cache<Integer, String> cache = new Cache<Integer, String>() {
        @Override
        protected long now() {
            return now.get();
        }
    };
    cache.setExpireAfterAccessNanos(1);
    now.set(0);
    for (int i = 0; i < numberOfEntries; i++) {
        cache.put(i, Integer.toString(i));
    }
    now.set(1);
    Set<Integer> promotedKeys = new HashSet<>();
    for (int i = 0; i < numberOfEntries; i++) {
        if (rarely()) {
            cache.get(i);
            promotedKeys.add(i);
        }
    }
    now.set(2);
    cache.refresh();
    assertEquals(promotedKeys.size(), cache.count());
    for (int i = 0; i < numberOfEntries; i++) {
        if (promotedKeys.contains(i)) {
            assertNotNull(cache.get(i));
        } else {
            assertNull(cache.get(i));
        }
    }
}
 
Example 6
Project: GitHub   File: RealmTests.java   View Source Code Vote up 5 votes
@Test
public void waitForChange_emptyDataChange() throws InterruptedException {
    final CountDownLatch bgRealmOpened = new CountDownLatch(1);
    final CountDownLatch bgRealmClosed = new CountDownLatch(1);
    final AtomicBoolean bgRealmChangeResult = new AtomicBoolean(false);
    final AtomicLong bgRealmWaitForChangeResult = new AtomicLong(0);

    // Waits in background.
    final CountDownLatch signalTestFinished = new CountDownLatch(1);
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            Realm realm = Realm.getInstance(realmConfig);
            bgRealmOpened.countDown();
            bgRealmChangeResult.set(realm.waitForChange());
            bgRealmWaitForChangeResult.set(realm.where(AllTypes.class).count());
            realm.close();
            bgRealmClosed.countDown();
        }
    });
    thread.start();

    TestHelper.awaitOrFail(bgRealmOpened);
    realm.beginTransaction();
    realm.commitTransaction();
    TestHelper.awaitOrFail(bgRealmClosed);
    assertTrue(bgRealmChangeResult.get());
    assertEquals(0, bgRealmWaitForChangeResult.get());
}
 
Example 7
Project: openjdk-jdk10   File: AtomicLongTest.java   View Source Code Vote up 5 votes
/**
 * get returns the last value set
 */
public void testGetSet() {
    AtomicLong ai = new AtomicLong(1);
    assertEquals(1, ai.get());
    ai.set(2);
    assertEquals(2, ai.get());
    ai.set(-3);
    assertEquals(-3, ai.get());
}
 
Example 8
Project: openjdk-jdk10   File: AtomicLongTest.java   View Source Code Vote up 5 votes
/**
 * floatValue returns current value.
 */
public void testFloatValue() {
    AtomicLong ai = new AtomicLong();
    assertEquals(0.0f, ai.floatValue());
    for (long x : VALUES) {
        ai.set(x);
        assertEquals((float)x, ai.floatValue());
    }
}
 
Example 9
Project: reactive-grpc   File: BackpressureIntegrationTest.java   View Source Code Vote up 5 votes
private static void updateNumberOfWaits(AtomicLong start, AtomicLong maxTime) {
    Long now = System.currentTimeMillis();
    Long startValue = start.get();
    if (startValue != 0 && now - startValue > 1000) {
        maxTime.incrementAndGet();
    }
    start.set(now);
}
 
Example 10
Project: reading-and-annotate-rocketmq-3.4.6   File: PullAPIWrapper.java   View Source Code Vote up 5 votes
public void updatePullFromWhichNode(final MessageQueue mq, final long brokerId) {
    AtomicLong suggest = this.pullFromWhichNodeTable.get(mq);
    if (null == suggest) {
        this.pullFromWhichNodeTable.put(mq, new AtomicLong(brokerId));
    }
    else {
        suggest.set(brokerId);
    }
}
 
Example 11
Project: boohee_v5.6   File: OperatorObserveOn.java   View Source Code Vote up 5 votes
void pollQueue() {
    int emitted = 0;
    AtomicLong localRequested = this.requested;
    AtomicLong localCounter = this.counter;
    do {
        localCounter.set(1);
        long produced = 0;
        long r = localRequested.get();
        while (!this.child.isUnsubscribed()) {
            if (this.finished) {
                Throwable error = this.error;
                if (error != null) {
                    this.queue.clear();
                    this.child.onError(error);
                    return;
                } else if (this.queue.isEmpty()) {
                    this.child.onCompleted();
                    return;
                }
            }
            if (r > 0) {
                Object o = this.queue.poll();
                if (o != null) {
                    this.child.onNext(this.on.getValue(o));
                    r--;
                    emitted++;
                    produced++;
                }
            }
            if (produced > 0 && localRequested.get() != Long.MAX_VALUE) {
                localRequested.addAndGet(-produced);
            }
        }
        return;
    } while (localCounter.decrementAndGet() > 0);
    if (emitted > 0) {
        request((long) emitted);
    }
}
 
Example 12
Project: elasticsearch_my   File: ESIntegTestCase.java   View Source Code Vote up 5 votes
/**
 * Waits until at least a give number of document is visible for searchers
 *
 * @param numDocs         number of documents to wait for
 * @param maxWaitTime     if not progress have been made during this time, fail the test
 * @param maxWaitTimeUnit the unit in which maxWaitTime is specified
 * @param indexer         a {@link org.elasticsearch.test.BackgroundIndexer}. If supplied it will be first checked for documents indexed.
 *                        This saves on unneeded searches.
 * @return the actual number of docs seen.
 */
public long waitForDocs(final long numDocs, int maxWaitTime, TimeUnit maxWaitTimeUnit, @Nullable final BackgroundIndexer indexer)
    throws InterruptedException {
    final AtomicLong lastKnownCount = new AtomicLong(-1);
    long lastStartCount = -1;
    BooleanSupplier testDocs = () -> {
        if (indexer != null) {
            lastKnownCount.set(indexer.totalIndexedDocs());
        }
        if (lastKnownCount.get() >= numDocs) {
            try {
                long count = client().prepareSearch().setSize(0).setQuery(matchAllQuery()).execute().actionGet().getHits().getTotalHits();
                if (count == lastKnownCount.get()) {
                    // no progress - try to refresh for the next time
                    client().admin().indices().prepareRefresh().get();
                }
                lastKnownCount.set(count);
            } catch (Exception e) { // count now acts like search and barfs if all shards failed...
                logger.debug("failed to executed count", e);
                return false;
            }
            logger.debug("[{}] docs visible for search. waiting for [{}]", lastKnownCount.get(), numDocs);
        } else {
            logger.debug("[{}] docs indexed. waiting for [{}]", lastKnownCount.get(), numDocs);
        }
        return lastKnownCount.get() >= numDocs;
    };

    while (!awaitBusy(testDocs, maxWaitTime, maxWaitTimeUnit)) {
        if (lastStartCount == lastKnownCount.get()) {
            // we didn't make any progress
            fail("failed to reach " + numDocs + "docs");
        }
        lastStartCount = lastKnownCount.get();
    }
    return lastKnownCount.get();
}
 
Example 13
Project: elasticsearch_my   File: BootstrapCheckTests.java   View Source Code Vote up 5 votes
public void testFileDescriptorLimits() throws NodeValidationException {
    final boolean osX = randomBoolean(); // simulates OS X versus non-OS X
    final int limit = osX ? 10240 : 1 << 16;
    final AtomicLong maxFileDescriptorCount = new AtomicLong(randomIntBetween(1, limit - 1));
    final BootstrapChecks.FileDescriptorCheck check;
    if (osX) {
        check = new BootstrapChecks.OsXFileDescriptorCheck() {
            @Override
            long getMaxFileDescriptorCount() {
                return maxFileDescriptorCount.get();
            }
        };
    } else {
        check = new BootstrapChecks.FileDescriptorCheck() {
            @Override
            long getMaxFileDescriptorCount() {
                return maxFileDescriptorCount.get();
            }
        };
    }

    final NodeValidationException e =
            expectThrows(NodeValidationException.class,
                    () -> BootstrapChecks.check(true, Collections.singletonList(check), "testFileDescriptorLimits"));
    assertThat(e.getMessage(), containsString("max file descriptors"));

    maxFileDescriptorCount.set(randomIntBetween(limit + 1, Integer.MAX_VALUE));

    BootstrapChecks.check(true, Collections.singletonList(check), "testFileDescriptorLimits");

    // nothing should happen if current file descriptor count is
    // not available
    maxFileDescriptorCount.set(-1);
    BootstrapChecks.check(true, Collections.singletonList(check), "testFileDescriptorLimits");
}
 
Example 14
Project: elasticsearch_my   File: CacheTests.java   View Source Code Vote up 5 votes
public void testExpirationAfterAccess() {
    AtomicLong now = new AtomicLong();
    Cache<Integer, String> cache = new Cache<Integer, String>() {
        @Override
        protected long now() {
            return now.get();
        }
    };
    cache.setExpireAfterAccessNanos(1);
    List<Integer> evictedKeys = new ArrayList<>();
    cache.setRemovalListener(notification -> {
        assertEquals(RemovalNotification.RemovalReason.EVICTED, notification.getRemovalReason());
        evictedKeys.add(notification.getKey());
    });
    now.set(0);
    for (int i = 0; i < numberOfEntries; i++) {
        cache.put(i, Integer.toString(i));
    }
    now.set(1);
    for (int i = numberOfEntries; i < 2 * numberOfEntries; i++) {
        cache.put(i, Integer.toString(i));
    }
    now.set(2);
    cache.refresh();
    assertEquals(numberOfEntries, cache.count());
    for (int i = 0; i < evictedKeys.size(); i++) {
        assertEquals(i, (int) evictedKeys.get(i));
    }
    Set<Integer> remainingKeys = new HashSet<>();
    for (Integer key : cache.keys()) {
        remainingKeys.add(key);
    }
    for (int i = numberOfEntries; i < 2 * numberOfEntries; i++) {
        assertTrue(remainingKeys.contains(i));
    }
}
 
Example 15
Project: OpenJSharp   File: Dialog.java   View Source Code Vote up 4 votes
/**
 * @return true if we actually showed, false if we just called toFront()
 */
private boolean conditionalShow(Component toFocus, AtomicLong time) {
    boolean retval;

    closeSplashScreen();

    synchronized (getTreeLock()) {
        if (peer == null) {
            addNotify();
        }
        validateUnconditionally();
        if (visible) {
            toFront();
            retval = false;
        } else {
            visible = retval = true;

            // check if this dialog should be modal blocked BEFORE calling peer.show(),
            // otherwise, a pair of FOCUS_GAINED and FOCUS_LOST may be mistakenly
            // generated for the dialog
            if (!isModal()) {
                checkShouldBeBlocked(this);
            } else {
                modalDialogs.add(this);
                modalShow();
            }

            if (toFocus != null && time != null && isFocusable() &&
                isEnabled() && !isModalBlocked()) {
                // keep the KeyEvents from being dispatched
                // until the focus has been transfered
                time.set(Toolkit.getEventQueue().getMostRecentKeyEventTime());
                KeyboardFocusManager.getCurrentKeyboardFocusManager().
                    enqueueKeyEvents(time.get(), toFocus);
            }

            // This call is required as the show() method of the Dialog class
            // does not invoke the super.show(). So wried... :(
            mixOnShowing();

            peer.setVisible(true); // now guaranteed never to block
            if (isModalBlocked()) {
                modalBlocker.toFront();
            }

            setLocationByPlatform(false);
            for (int i = 0; i < ownedWindowList.size(); i++) {
                Window child = ownedWindowList.elementAt(i).get();
                if ((child != null) && child.showWithParent) {
                    child.show();
                    child.showWithParent = false;
                }       // endif
            }   // endfor
            Window.updateChildFocusableWindowState(this);

            createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
                                  this, parent,
                                  HierarchyEvent.SHOWING_CHANGED,
                                  Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
            if (componentListener != null ||
                    (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||
                    Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) {
                ComponentEvent e =
                    new ComponentEvent(this, ComponentEvent.COMPONENT_SHOWN);
                Toolkit.getEventQueue().postEvent(e);
            }
        }
    }

    if (retval && (state & OPENED) == 0) {
        postWindowEvent(WindowEvent.WINDOW_OPENED);
        state |= OPENED;
    }

    return retval;
}
 
Example 16
Project: monarch   File: WriteAheadLog.java   View Source Code Vote up 4 votes
/**
 * Initialize the WriteAheadLog instance
 * 
 * @param directory WAL directory
 * @param recordLimit Max number of records a WAL file can contain.
 * @throws IOException
 */
synchronized public void init(Path directory, int recordLimit, int fileExpirationTimeMins)
    throws IOException {
  if (initialized) {
    throw new RuntimeException("WriteAheadLog can not be initialized multiple times");
  }
  walDirectory = directory;
  this.recordLimit = recordLimit;
  numFiles = 0;
  this.fileExpirationTimeMins = fileExpirationTimeMins;
  /* Create the directory */
  if (!directory.toFile().exists()) {
    if (!directory.toFile().mkdir()) { /* No other thread should create this file */
      throw new RuntimeException("Failed to create directory");
    }
  }
  /* populate the bucketId -> file seq Id map */
  bucketSeqNoMap = new HashMap<>();
  String[] walFiles = directory.toFile().list();
  if (walFiles != null && walFiles.length != 0) {
    for (String walFile : walFiles) {
      String tableName = getTableName(walFile);
      int partitionId = getPartitionId(walFile);
      long seqNumber = getSeqNumber(walFile);
      if (tableName != null && partitionId != -1 && seqNumber != -1) {
        AtomicLong mapValue = bucketSeqNoMap.get(tableName + "_" + partitionId);
        if (mapValue != null) {
          long savedSeqNumber = mapValue.get();
          if (savedSeqNumber < seqNumber + 1) {
            mapValue.set(seqNumber + 1);
          }
        } else {
          bucketSeqNoMap.put(tableName + "_" + partitionId, new AtomicLong(seqNumber + 1));
        }
      }
      if (walFile.endsWith(WAL_INPROGRESS_SUFFIX)) {
        markFileDone(walDirectory + "/" + walFile);
      }
    }
  }

  byte[] dsName = null;
  try {
    dsName = Bytes.toBytes(MCacheFactory.getAnyInstance().getDistributedSystem().getName());
  } catch (CacheClosedException cce) {
    dsName = Bytes.toBytes("==DsNameNotSet==");
    // logger.error("Distributed system name not set", cce);
  }

  nodeId = new byte[dsName.length + Integer.SIZE / 8];
  System.arraycopy(Bytes.toBytes(dsName.length), 0, nodeId, 0, Integer.SIZE / 8);
  System.arraycopy(dsName, 0, nodeId, Integer.SIZE / 8, dsName.length);
  initialized = true;
}
 
Example 17
Project: openjdk-jdk10   File: Dialog.java   View Source Code Vote up 4 votes
/**
 * @return true if we actually showed, false if we just called toFront()
 */
@SuppressWarnings("deprecation")
private boolean conditionalShow(Component toFocus, AtomicLong time) {
    boolean retval;

    closeSplashScreen();

    synchronized (getTreeLock()) {
        if (peer == null) {
            addNotify();
        }
        validateUnconditionally();
        if (visible) {
            toFront();
            retval = false;
        } else {
            visible = retval = true;

            // check if this dialog should be modal blocked BEFORE calling peer.show(),
            // otherwise, a pair of FOCUS_GAINED and FOCUS_LOST may be mistakenly
            // generated for the dialog
            if (!isModal()) {
                checkShouldBeBlocked(this);
            } else {
                modalDialogs.add(this);
                modalShow();
            }

            if (toFocus != null && time != null && isFocusable() &&
                isEnabled() && !isModalBlocked()) {
                // keep the KeyEvents from being dispatched
                // until the focus has been transferred
                time.set(Toolkit.getEventQueue().getMostRecentKeyEventTime());
                KeyboardFocusManager.getCurrentKeyboardFocusManager().
                    enqueueKeyEvents(time.get(), toFocus);
            }

            // This call is required as the show() method of the Dialog class
            // does not invoke the super.show(). So wried... :(
            mixOnShowing();

            peer.setVisible(true); // now guaranteed never to block
            if (isModalBlocked()) {
                modalBlocker.toFront();
            }

            setLocationByPlatform(false);
            for (int i = 0; i < ownedWindowList.size(); i++) {
                Window child = ownedWindowList.elementAt(i).get();
                if ((child != null) && child.showWithParent) {
                    child.show();
                    child.showWithParent = false;
                }       // endif
            }   // endfor
            Window.updateChildFocusableWindowState(this);

            createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
                                  this, parent,
                                  HierarchyEvent.SHOWING_CHANGED,
                                  Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
            if (componentListener != null ||
                    (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||
                    Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) {
                ComponentEvent e =
                    new ComponentEvent(this, ComponentEvent.COMPONENT_SHOWN);
                Toolkit.getEventQueue().postEvent(e);
            }
        }
    }

    if (retval && (state & OPENED) == 0) {
        postWindowEvent(WindowEvent.WINDOW_OPENED);
        state |= OPENED;
    }

    return retval;
}
 
Example 18
Project: ditb   File: TestMultiVersionConcurrencyControl.java   View Source Code Vote up 4 votes
public void testParallelism() throws Exception {
  final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl();

  final AtomicBoolean finished = new AtomicBoolean(false);

  // fail flag for the reader thread
  final AtomicBoolean readerFailed = new AtomicBoolean(false);
  final AtomicLong failedAt = new AtomicLong();
  Runnable reader = new Runnable() {
    public void run() {
      long prev = mvcc.getReadPoint();
      while (!finished.get()) {
        long newPrev = mvcc.getReadPoint();
        if (newPrev < prev) {
          // serious problem.
          System.out.println("Reader got out of order, prev: " + prev + " next was: " + newPrev);
          readerFailed.set(true);
          // might as well give up
          failedAt.set(newPrev);
          return;
        }
      }
    }
  };

  // writer thread parallelism.
  int n = 20;
  Thread[] writers = new Thread[n];
  AtomicBoolean[] statuses = new AtomicBoolean[n];
  Thread readThread = new Thread(reader);

  for (int i = 0; i < n; ++i) {
    statuses[i] = new AtomicBoolean(true);
    writers[i] = new Thread(new Writer(finished, mvcc, statuses[i]));
    writers[i].start();
  }
  readThread.start();

  try {
    Thread.sleep(10 * 1000);
  } catch (InterruptedException ex) {
  }

  finished.set(true);

  readThread.join();
  for (int i = 0; i < n; ++i) {
    writers[i].join();
  }

  // check failure.
  assertFalse(readerFailed.get());
  for (int i = 0; i < n; ++i) {
    assertTrue(statuses[i].get());
  }
}
 
Example 19
Project: boohee_v5.6   File: FieldDeserializer.java   View Source Code Vote up 4 votes
public void setValue(Object object, Object value) {
    Method method = this.fieldInfo.getMethod();
    if (method != null) {
        try {
            if (this.fieldInfo.isGetOnly()) {
                if (this.fieldInfo.getFieldClass() == AtomicInteger.class) {
                    AtomicInteger atomic = (AtomicInteger) method.invoke(object, new Object[0]);
                    if (atomic != null) {
                        atomic.set(((AtomicInteger) value).get());
                        return;
                    }
                    return;
                } else if (this.fieldInfo.getFieldClass() == AtomicLong.class) {
                    AtomicLong atomic2 = (AtomicLong) method.invoke(object, new Object[0]);
                    if (atomic2 != null) {
                        atomic2.set(((AtomicLong) value).get());
                        return;
                    }
                    return;
                } else if (this.fieldInfo.getFieldClass() == AtomicBoolean.class) {
                    AtomicBoolean atomic3 = (AtomicBoolean) method.invoke(object, new Object[0]);
                    if (atomic3 != null) {
                        atomic3.set(((AtomicBoolean) value).get());
                        return;
                    }
                    return;
                } else if (Map.class.isAssignableFrom(method.getReturnType())) {
                    Map map = (Map) method.invoke(object, new Object[0]);
                    if (map != null) {
                        map.putAll((Map) value);
                        return;
                    }
                    return;
                } else {
                    Collection collection = (Collection) method.invoke(object, new Object[0]);
                    if (collection != null) {
                        collection.addAll((Collection) value);
                        return;
                    }
                    return;
                }
            } else if (value != null || !this.fieldInfo.getFieldClass().isPrimitive()) {
                method.invoke(object, new Object[]{value});
                return;
            } else {
                return;
            }
        } catch (Exception e) {
            throw new JSONException("set property error, " + this.fieldInfo.getName(), e);
        }
    }
    Field field = this.fieldInfo.getField();
    if (field != null) {
        try {
            field.set(object, value);
        } catch (Exception e2) {
            throw new JSONException("set property error, " + this.fieldInfo.getName(), e2);
        }
    }
}
 
Example 20
Project: hekate   File: LocalMetricsServiceTest.java   View Source Code Vote up 2 votes
@Test
public void testDynamicListeners() throws Exception {
    AtomicLong probe = new AtomicLong(100);

    metrics.register(new CounterConfig("c"));
    metrics.register(new ProbeConfig("p").withInitValue(100).withProbe(probe::get));

    metrics.counter("c").add(1000);

    MetricsListener listener = this::putAsyncEvent;

    metrics.addListener(listener);

    assertTrue(metrics.listeners().contains(listener));

    MetricsUpdateEvent event1 = getAsyncEvent();

    Map<String, Metric> snapshot = event1.allMetrics();

    assertNotNull(snapshot);

    assertEquals(1000, snapshot.get("c").value());
    assertEquals(100, snapshot.get("p").value());

    metrics.counter("c").add(1000);
    probe.set(200);

    MetricsUpdateEvent event2 = getAsyncEvent();

    assertTrue(event1.tick() < event2.tick());

    snapshot = event2.allMetrics();

    assertEquals(2000, snapshot.get("c").value());
    assertEquals(200, snapshot.get("p").value());

    metrics.removeListener(listener);

    assertFalse(metrics.listeners().contains(listener));

    probe.set(100);
    metrics.counter("c").add(1000);

    expect(TimeoutException.class, () ->
        getAsyncEvent(TEST_METRICS_REFRESH_INTERVAL * 2, TimeUnit.MILLISECONDS)
    );
}