[ISSUE #4349] fix negative index when index reach Integer.MAX_VALUE (#4447)

Co-authored-by: wuguoqing <wuguoqing@zhuanzhuan.com>
This commit is contained in:
Wushiyii
2022-06-13 09:39:40 +08:00
committed by GitHub
co-authored by wuguoqing
parent 73b9ac82bc
commit f08c79ff9f
2 changed files with 17 additions and 1 deletions
@@ -22,6 +22,7 @@ import java.util.Random;
public class ThreadLocalIndex {
private final ThreadLocal<Integer> threadLocalIndex = new ThreadLocal<Integer>();
private final Random random = new Random();
private final static int POSITIVE_MASK = 0x7FFFFFFF;
public int incrementAndGet() {
Integer index = this.threadLocalIndex.get();
@@ -31,7 +32,7 @@ public class ThreadLocalIndex {
}
this.threadLocalIndex.set(++index);
return Math.abs(index);
return Math.abs(index & POSITIVE_MASK);
}
@Override
@@ -16,6 +16,7 @@
*/
package org.apache.rocketmq.client.common;
import java.lang.reflect.Field;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -36,4 +37,18 @@ public class ThreadLocalIndexTest {
assertThat(initialVal >= 0).isTrue();
}
@Test
public void testIncrementAndGet3() throws Exception {
ThreadLocalIndex localIndex = new ThreadLocalIndex();
Field threadLocalIndexField = ThreadLocalIndex.class.getDeclaredField("threadLocalIndex");
ThreadLocal<Integer> mockThreadLocal = new ThreadLocal<Integer>();
mockThreadLocal.set(Integer.MAX_VALUE);
threadLocalIndexField.setAccessible(true);
threadLocalIndexField.set(localIndex, mockThreadLocal);
int initialVal = localIndex.incrementAndGet();
assertThat(initialVal >= 0).isTrue();
}
}