- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringImmutableTest.java
More file actions
Latest commit
79 lines (60 loc) · 2.04 KB
/
Copy pathStringImmutableTest.java
File metadata and controls
79 lines (60 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
packagebasics;
importorg.junit.jupiter.api.Test;
importjava.util.HashMap;
importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.Executors;
importjava.util.concurrent.atomic.AtomicBoolean;
importstaticorg.junit.jupiter.api.Assertions.*;
publicclassStringImmutableTest {
@Test
publicvoid리터럴_String은_같은메모리를_참조한다() {
//given
Strings1 = "minseok";
Strings2 = "minseok";
//when
//then
assertTrue(s1 == s2);
}
@Test
publicvoidString불변객체확인() {
//given
Strings1 = "minseok";
//when
changeStringToAlice(s1);
//then
assertTrue(s1.equals("minseok"));
}
privatevoidchangeStringToAlice(Strings1) {
s1= "Alice";
}
@Test
voidstringIsThreadSafe() {
// given
StringsharedString = "immutableString";
AtomicBooleanisConsistent = newAtomicBoolean(true);
// when
ExecutorServiceexecutorService = Executors.newFixedThreadPool(10);
for (inti = 0; i < 10; i++) {
executorService.execute(() -> {
// Simulate concurrent access
if (!sharedString.equals("immutableString")) {
isConsistent.set(false);
}
});
}
// Shutdown the executor and wait for tasks to complete
executorService.shutdown();
while (!executorService.isTerminated()) {
// Wait for all threads to finish
}
// then
assertTrue(isConsistent.get(), "String is not thread-safe!");
HashMap<String, String> immutableMap = newHashMap<>();
Stringkey = "immutableKey";
immutableMap.put(key, "immutableValue");
// Attempt to modify the key (not possible since String is immutable)
key = "modifiedKey";
System.out.println("Immutable Map Retrieval:");
System.out.println("Value for 'immutableKey': " + immutableMap.get("immutableKey")); // Works
}
}