Is String.intern() thread safe

前端 未结 2 1972

I would like to use String.intern() in Java to save memory (use the internal pool for strings with the same content). I call this method from different threads. Is it a problem?

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-13 09:54

    The short answer to your question is yes. It's thread-safe.

    However, you might want to reconsider using this facility to reduce memory consumption. The reason is that you are unable to remove any entires from the list of interned strings. A better solution would be to create your own facility for this. All you'd need is to store your strings in a HashMap like so:

    public String getInternedString(String s) {
        synchronized(strings) {
            String found = strings.get(s);
            if(found == null) {
                strings.put(s, s);
                found = s;
            }
            return found;
        }
    }
    

提交回复
热议问题