File tree Expand file tree Collapse file tree 2 files changed +37
-3
lines changed
main/java/co/elastic/apm/agent/collections
test/java/co/elastic/apm/agent/collections Expand file tree Collapse file tree 2 files changed +37
-3
lines changed Original file line number Diff line number Diff line change 2727import java .util .Arrays ;
2828
2929public class LongList {
30+ private static final int MAX_ARRAY_SIZE = Integer .MAX_VALUE - 8 ;
3031 private static final int DEFAULT_CAPACITY = 16 ;
3132 private long [] longs ;
3233 private int size ;
@@ -58,9 +59,20 @@ public void addAll(LongList other) {
5859 size += other .size ;
5960 }
6061
61- private void ensureCapacity (int size ) {
62- if (longs .length < size ) {
63- longs = Arrays .copyOf (longs , longs .length * 2 );
62+ private void ensureCapacity (long minCapacity ) {
63+ if (longs .length < minCapacity ) {
64+ longs = Arrays .copyOf (longs , newCapacity (minCapacity , longs .length ));
65+ }
66+ }
67+
68+ static int newCapacity (long minCapacity , long oldCapacity ) {
69+ long growBy50Percent = oldCapacity + (oldCapacity >> 1 );
70+ if (minCapacity <= growBy50Percent ) {
71+ return (int ) growBy50Percent ;
72+ } else if (minCapacity <= MAX_ARRAY_SIZE ) {
73+ return (int ) minCapacity ;
74+ } else {
75+ throw new OutOfMemoryError ();
6476 }
6577 }
6678
Original file line number Diff line number Diff line change @@ -69,6 +69,28 @@ void testAddAll() {
6969 assertThat (this .longList .get (2 )).isEqualTo (44 );
7070 }
7171
72+ @ Test
73+ void testAddAllLargeList () {
74+ longList .add (42 );
75+ LongList list2 = new LongList ();
76+ for (int i = 0 ; i < 42 ; i ++) {
77+ list2 .add (i );
78+ }
79+ longList .addAll (list2 );
80+ assertThat (this .longList .getSize ()).isEqualTo (43 );
81+ assertThat (this .longList .get (0 )).isEqualTo (42 );
82+ assertThat (this .longList .get (1 )).isEqualTo (0 );
83+ assertThat (this .longList .get (2 )).isEqualTo (1 );
84+ }
85+
86+ @ Test
87+ void testNewCapacity () {
88+ assertThat (LongList .newCapacity (1 , 0 )).isEqualTo (1 );
89+ assertThat (LongList .newCapacity (42 , 4 )).isEqualTo (42 );
90+ assertThat (LongList .newCapacity (5 , 4 )).isEqualTo (6 );
91+ assertThatThrownBy (() -> LongList .newCapacity (Integer .MAX_VALUE , 4 )).isInstanceOf (OutOfMemoryError .class );
92+ }
93+
7294 @ Test
7395 void testOutOfBounds () {
7496 assertThatThrownBy (() -> longList .get (0 )).isInstanceOf (IndexOutOfBoundsException .class );
You can’t perform that action at this time.
0 commit comments