Prakhar Gupta
Prakhar Gupta

Reputation: 31

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. ?

Upvotes: 1

Views: 2344

Answers (3)

Tagir Valeev
Tagir Valeev

Reputation: 100169

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);

Upvotes: 5

Chris K
Chris K

Reputation: 11907

One can also call String.intern(), which is essentially a string pool that is already implemented for us.

However be warned that object pools in Java are often the wrong thing to do, whether they are String.intern or ConcurrentHashMap etc. Double check your use case by measuring the impact. Examples of when to use resource pools is when the objects being pooled are both expensive to create and limited in number; for example network and database connections.

The hidden cost that most people forget is the cost to GC. GC cost is related to how many live objects one has on the heap, and the JVM is not very good with objects that live for a fair while and then die. It is much better with objects that die young, or never die.

Upvotes: 0

jwenting
jwenting

Reputation: 5663

The String constant pool is a well defined term in Java and is implemented by the JVM. You can't replace it by something you create in your Java program, you'd have to write your own JVM.

If you mean you want some sort of String pool inside your application for storing Strings that your application uses over and over again (say a centralized place for texts to display on a user interface) a ResourceBundle is a good way to go, which is essentially a wrapper around a Map.

Upvotes: 3

Related Questions