Prakhar Gupta Prakhar Gupta - 2 months ago 6
Java Question

How to implement our own string constant pool through a program in java?

How is the string constant pool implemented in java?
How can we make the same local. ?

Answer

Here's very simple implementation of object pool:

public class ObjectPool<T> {
    private ConcurrentMap<T, T> map = new ConcurrentHashMap<>();

    public T get(T object) {
        T old = map.putIfAbsent( object, object );
        return old == null ? object : old;
    }
}

Now to create a pool of strings use

final ObjectPool<String> stringPool = new ObjectPool<>();

You can use it to deduplicate the strings in your program:

String deduplicatedStr = stringPool.get(str);
Comments