nairavs
nairavs

Reputation: 509

String intern for synchronisation

public final static HashMap<String,Object> map = new HashMap<String, Object>();//global variable

//this is a post method

    String forSync = null;

//somewhere here init forSync
...

        if(forSync != null){
            Object obj = null;
            synchronized(map){
                obj = map.get(forSync);//can be not empty
                if(obj == null){
                    obj  = new Object();
                    map.put(forSync.intern(), obj );
                }
            }
        synchronized(obj){
//sync block
}

String don't synchronize properly . Will this work or I should change

        obj = map.get(forSync);
        obj = map.get(forSync.intern());

could you please explain what will be difference if I get with and with ought .intern() . I tried and the result was the same , It seems to me that I don't understand properly how intern works.

Upvotes: 2

Views: 524

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328584

As far as synchronization and thread-safety are concerned, intern() makes no difference. Map uses the string's hashcode to look up values and this value doesn't change (String is an immutable or a "value type"). It's always safe to use as key. synchronized on the map will make sure that the internal data structure of the map can't be corrupted by parallel access. It has no effect on the String itself.

String.intern() sometimes makes a difference if you have many strings with the same value. In that case, you can use the pool to save some memory. Many here means 100'000+. It doesn't make sense to use this for a few thousand strings; Java is optimized to death in this area. Just putting values into the pool often simply bloats the pool without much benefit.

Upvotes: 1

Related Questions