Suppose I have a class which wraps a HashMap as follows:
public final class MyClass{
private final Map<String, String> map;
//Called by Thread1
public MyClass( int size ){
this.map = new HashMap<String, String>( size );
}
//Only ever called by Thread2
public final String put( String key, String val ){
return map.put( key, value );
}
//Only ever called by Thread2
public final String get( String key ){
return map.get( key );
}
//Only ever called by Thread2
public final void printMap( ){
//Format and print the contents of the map
}
}
This class is initialized via "Thread1". However, the put, get, printMap and other operations are only ever called by "Thread2".
Am I correct in understanding that this class is thread safe as:
Since the reference to the map is declared final, all other threads would see the initial state of the map (happens-before is established).
Since put/get/printMap/etc are only ever called by Thread2, there is no need for mutual-exclusion.
Thank you