Skip to content

Commit

Permalink
AtomicMaxUpdater refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
emeroad committed Jan 21, 2015
1 parent 52027a7 commit 5e9adb0
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 6 deletions.
@@ -1,28 +1,31 @@
package com.navercorp.pinpoint.bootstrap.interceptor;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
* @author emeroad
*/
public class AtomicMaxUpdater {

private final AtomicInteger maxIndex = new AtomicInteger(-1);
private static final AtomicIntegerFieldUpdater<AtomicMaxUpdater> UPDATER = AtomicIntegerFieldUpdater.newUpdater(AtomicMaxUpdater.class, "maxIndex");

public boolean updateMax(int max) {
private volatile int maxIndex = 0;

public boolean update(int max) {
while (true) {
final int currentMax = maxIndex.get();
final int currentMax = getIndex();
if (currentMax >= max) {
return false;
}
final boolean update = maxIndex.compareAndSet(currentMax, max);
final boolean update = UPDATER.compareAndSet(this, currentMax, max);
if (update) {
return true;
}
}
}


public int getIndex() {
return maxIndex.get();
return UPDATER.get(this);
}
}
@@ -0,0 +1,42 @@
/*
* Copyright 2014 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.navercorp.pinpoint.bootstrap.interceptor;

import junit.framework.Assert;
import org.junit.Test;

/**
* @author emeroad
*/
public class AtomicMaxUpdaterTest {
@Test
public void update() {
AtomicMaxUpdater updater = new AtomicMaxUpdater();

Assert.assertFalse(updater.update(0));


Assert.assertTrue(updater.update(1));

Assert.assertTrue(updater.update(10));

Assert.assertFalse(updater.update(5));
Assert.assertEquals(updater.getIndex(), 10);


}
}

0 comments on commit 5e9adb0

Please sign in to comment.