diff --git a/src/main/java/com/github/_1c_syntax/utils/StringInterner.java b/src/main/java/com/github/_1c_syntax/utils/StringInterner.java new file mode 100644 index 0000000..9629e37 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/utils/StringInterner.java @@ -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 map = new ConcurrentHashMap<>(); + + public String intern(String string) { + String exist = map.putIfAbsent(string, string); + return (exist == null) ? string : exist; + } + + public void clear() { + map.clear(); + } +} diff --git a/src/test/java/com/github/_1c_syntax/utils/StringInternerTest.java b/src/test/java/com/github/_1c_syntax/utils/StringInternerTest.java new file mode 100644 index 0000000..580c41f --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/utils/StringInternerTest.java @@ -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); + } +} \ No newline at end of file