Skip to content

Commit

Permalink
StringInterner
Browse files Browse the repository at this point in the history
  • Loading branch information
nixel2007 committed Jan 18, 2022
1 parent 5d9a70c commit d814026
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/main/java/com/github/_1c_syntax/utils/StringInterner.java
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 src/test/java/com/github/_1c_syntax/utils/StringInternerTest.java
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);
}
}

0 comments on commit d814026

Please sign in to comment.