Skip to content

Commit 5e0d1e8

Browse files
tomekl007pedja4
authored andcommitted
BAEL-814 unsafe (eugenp#1645)
* code for the unsafe article * more descriptive example * proper eng * better test name * free memory call * java 8 style
1 parent 2dbca95 commit 5e0d1e8

3 files changed

Lines changed: 190 additions & 0 deletions

File tree

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.baeldung.unsafe;
2+
3+
import sun.misc.Unsafe;
4+
5+
import java.lang.reflect.Field;
6+
7+
class CASCounter {
8+
private final Unsafe unsafe;
9+
private volatile long counter = 0;
10+
private long offset;
11+
12+
private Unsafe getUnsafe() throws IllegalAccessException, NoSuchFieldException {
13+
Field f = Unsafe.class.getDeclaredField("theUnsafe");
14+
f.setAccessible(true);
15+
return (Unsafe) f.get(null);
16+
}
17+
18+
public CASCounter() throws Exception {
19+
unsafe = getUnsafe();
20+
offset = unsafe.objectFieldOffset(CASCounter.class.getDeclaredField("counter"));
21+
}
22+
23+
public void increment() {
24+
long before = counter;
25+
while (!unsafe.compareAndSwapLong(this, offset, before, before + 1)) {
26+
before = counter;
27+
}
28+
}
29+
30+
public long getCounter() {
31+
return counter;
32+
}
33+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.baeldung.unsafe;
2+
3+
import sun.misc.Unsafe;
4+
5+
import java.lang.reflect.Field;
6+
7+
class OffHeapArray {
8+
private final static int BYTE = 1;
9+
private long size;
10+
private long address;
11+
12+
private Unsafe getUnsafe() throws IllegalAccessException, NoSuchFieldException {
13+
Field f = Unsafe.class.getDeclaredField("theUnsafe");
14+
f.setAccessible(true);
15+
return (Unsafe) f.get(null);
16+
}
17+
18+
public OffHeapArray(long size) throws NoSuchFieldException, IllegalAccessException {
19+
this.size = size;
20+
address = getUnsafe().allocateMemory(size * BYTE);
21+
}
22+
23+
public void set(long i, byte value) throws NoSuchFieldException, IllegalAccessException {
24+
getUnsafe().putByte(address + i * BYTE, value);
25+
}
26+
27+
public int get(long idx) throws NoSuchFieldException, IllegalAccessException {
28+
return getUnsafe().getByte(address + idx * BYTE);
29+
}
30+
31+
public long size() {
32+
return size;
33+
}
34+
35+
public void freeMemory() throws NoSuchFieldException, IllegalAccessException {
36+
getUnsafe().freeMemory(address);
37+
}
38+
39+
}
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
package com.baeldung.unsafe;
2+
3+
import org.junit.Before;
4+
import org.junit.Test;
5+
import sun.misc.Unsafe;
6+
7+
import java.io.IOException;
8+
import java.lang.reflect.Field;
9+
import java.util.concurrent.ExecutorService;
10+
import java.util.concurrent.Executors;
11+
import java.util.concurrent.TimeUnit;
12+
import java.util.stream.IntStream;
13+
14+
import static junit.framework.Assert.assertTrue;
15+
import static junit.framework.TestCase.assertEquals;
16+
17+
public class UnsafeTest {
18+
19+
private Unsafe unsafe;
20+
21+
@Before
22+
public void setup() throws NoSuchFieldException, IllegalAccessException {
23+
Field f = Unsafe.class.getDeclaredField("theUnsafe");
24+
f.setAccessible(true);
25+
unsafe = (Unsafe) f.get(null);
26+
}
27+
28+
29+
@Test
30+
public void givenClass_whenInitializeIt_thenShouldHaveDifferentStateWhenUseUnsafe() throws IllegalAccessException, InstantiationException {
31+
//when
32+
InitializationOrdering o1 = new InitializationOrdering();
33+
assertEquals(o1.getA(), 1);
34+
35+
//when
36+
InitializationOrdering o3 = (InitializationOrdering) unsafe.allocateInstance(InitializationOrdering.class);
37+
assertEquals(o3.getA(), 0);
38+
}
39+
40+
@Test
41+
public void givenPrivateMethod_whenUsingUnsafe_thenCanModifyPrivateField() throws NoSuchFieldException {
42+
//given
43+
SecretHolder secretHolder = new SecretHolder();
44+
45+
//when
46+
Field f = secretHolder.getClass().getDeclaredField("SECRET_VALUE");
47+
unsafe.putInt(secretHolder, unsafe.objectFieldOffset(f), 1);
48+
49+
//then
50+
assertTrue(secretHolder.secretIsDisclosed());
51+
}
52+
53+
@Test(expected = IOException.class)
54+
public void givenUnsafeThrowException_whenThrowCheckedException_thenNotNeedToCatchIt() {
55+
unsafe.throwException(new IOException());
56+
}
57+
58+
@Test
59+
public void givenArrayBiggerThatMaxInt_whenAllocateItOffHeapMemory_thenSuccess() throws NoSuchFieldException, IllegalAccessException {
60+
//given
61+
long SUPER_SIZE = (long) Integer.MAX_VALUE * 2;
62+
OffHeapArray array = new OffHeapArray(SUPER_SIZE);
63+
64+
//when
65+
int sum = 0;
66+
for (int i = 0; i < 100; i++) {
67+
array.set((long) Integer.MAX_VALUE + i, (byte) 3);
68+
sum += array.get((long) Integer.MAX_VALUE + i);
69+
}
70+
71+
//then
72+
assertEquals(array.size(), SUPER_SIZE);
73+
assertEquals(sum, 300);
74+
}
75+
76+
@Test
77+
public void givenUnsafeCompareAndSwap_whenUseIt_thenCounterYildCorrectLockFreeResults() throws Exception {
78+
//given
79+
int NUM_OF_THREADS = 1_000;
80+
int NUM_OF_INCREMENTS = 10_000;
81+
ExecutorService service = Executors.newFixedThreadPool(NUM_OF_THREADS);
82+
CASCounter casCounter = new CASCounter();
83+
84+
//when
85+
IntStream.rangeClosed(0, NUM_OF_THREADS - 1)
86+
.forEach(i -> service.submit(() -> IntStream
87+
.rangeClosed(0, NUM_OF_INCREMENTS - 1)
88+
.forEach(j -> casCounter.increment())));
89+
90+
service.shutdown();
91+
service.awaitTermination(1, TimeUnit.MINUTES);
92+
93+
//then
94+
assertEquals(NUM_OF_INCREMENTS * NUM_OF_THREADS, casCounter.getCounter());
95+
96+
}
97+
98+
class InitializationOrdering {
99+
private long a;
100+
101+
public InitializationOrdering() {
102+
this.a = 1;
103+
}
104+
105+
public long getA() {
106+
return this.a;
107+
}
108+
}
109+
110+
class SecretHolder {
111+
private int SECRET_VALUE = 0;
112+
113+
public boolean secretIsDisclosed() {
114+
return SECRET_VALUE == 1;
115+
}
116+
}
117+
118+
}

0 commit comments

Comments
 (0)