-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
72 additions
and
0 deletions.
There are no files selected for viewing
18 changes: 18 additions & 0 deletions
18
src/main/java/com/github/_1c_syntax/utils/StringInterner.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
package com.github._1c_syntax.utils; | ||
|
||
import java.util.Map; | ||
import java.util.concurrent.ConcurrentHashMap; | ||
|
||
public class StringInterner { | ||
|
||
private final Map<String, String> map = new ConcurrentHashMap<>(); | ||
|
||
public String intern(String string) { | ||
String exist = map.putIfAbsent(string, string); | ||
return (exist == null) ? string : exist; | ||
} | ||
|
||
public void clear() { | ||
map.clear(); | ||
} | ||
} |
54 changes: 54 additions & 0 deletions
54
src/test/java/com/github/_1c_syntax/utils/StringInternerTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
package com.github._1c_syntax.utils; | ||
|
||
import org.junit.jupiter.api.BeforeEach; | ||
import org.junit.jupiter.api.Test; | ||
|
||
import static org.junit.jupiter.api.Assertions.*; | ||
|
||
class StringInternerTest { | ||
|
||
private StringInterner interner; | ||
|
||
@BeforeEach | ||
public void init() { | ||
interner = new StringInterner(); | ||
} | ||
|
||
@Test | ||
void testIntern() { | ||
//given | ||
String s1 = new String("1"); | ||
String s2 = new String("1"); | ||
|
||
// when | ||
var intern1 = interner.intern(s1); | ||
|
||
// then | ||
assertEquals(s1, intern1); | ||
|
||
// when | ||
var intern2 = interner.intern(s2); | ||
|
||
// then | ||
assertEquals(s1, intern2); | ||
} | ||
|
||
@Test | ||
void testClear() { | ||
|
||
//given | ||
String s1 = new String("1"); | ||
String s2 = new String("1"); | ||
|
||
interner.intern(s1); | ||
|
||
// when | ||
interner.clear(); | ||
|
||
// when | ||
var intern = interner.intern(s2); | ||
|
||
// then | ||
assertEquals(s2, intern); | ||
} | ||
} |