Java Code Examples for java.util.concurrent.atomic.AtomicIntegerFieldUpdater#addAndGet()

The following examples show how to use java.util.concurrent.atomic.AtomicIntegerFieldUpdater#addAndGet() . 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 File: AtomicIntegerFieldUpdaterDemo.java    From JavaCommon with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Person person = new Person("zhangsan", 11, 170);
    person.setHobby(new Hobby("打球", "足球,篮球"));
    AtomicIntegerFieldUpdater<Person> atomicIntegerFieldUpdater = AtomicIntegerFieldUpdater.newUpdater(Person.class, "age");
    atomicIntegerFieldUpdater.addAndGet(person, 12);

    AtomicLongFieldUpdater<Person> atomicLongFieldUpdater = AtomicLongFieldUpdater.newUpdater(Person.class, "height");
    atomicLongFieldUpdater.addAndGet(person, 180);

    AtomicReferenceFieldUpdater<Person, Hobby> atomicReferenceFieldUpdater = AtomicReferenceFieldUpdater.newUpdater(Person.class, Hobby.class, "hobby");
    atomicReferenceFieldUpdater.getAndSet(person, new Hobby("打球", "排球,羽毛球"));

}
 
Example 2
Source File: Atomic8Test.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Object arguments for parameters of type T that are not
 * instances of the class passed to the newUpdater call will
 * result in a ClassCastException being thrown.
 */
public void testFieldUpdaters_ClassCastException() {
    // Use raw types to allow passing wrong object type, provoking CCE
    final AtomicLongFieldUpdater longUpdater = aLongFieldUpdater();
    final AtomicIntegerFieldUpdater intUpdater = anIntFieldUpdater();
    final AtomicReferenceFieldUpdater refUpdater = anIntegerFieldUpdater();
    final Object obj = new Object();
    for (Object x : new Object[]{ new Object(), null }) {
        Runnable[] throwingActions = {
            () -> longUpdater.get(x),
            () -> intUpdater.get(x),
            () -> refUpdater.get(x),

            () -> longUpdater.set(x, 17L),
            () -> intUpdater.set(x, 17),
            () -> refUpdater.set(x, (Integer) 17),

            () -> longUpdater.addAndGet(x, 17L),
            () -> intUpdater.addAndGet(x, 17),

            () -> longUpdater.getAndUpdate(x, y -> y),
            () -> intUpdater.getAndUpdate(x, y -> y),
            () -> refUpdater.getAndUpdate(x, y -> y),

            () -> longUpdater.compareAndSet(x, 17L, 42L),
            () -> intUpdater.compareAndSet(x, 17, 42),
            () -> refUpdater.compareAndSet(x, (Integer) 17, (Integer) 42),
        };
        assertThrows(ClassCastException.class, throwingActions);
    }
}