Since the objects we share in flyweight design pattern are immutable, I'm wondering if we need to take synchronization into consideration? Even when multiple threads try to access the same objects and insert into the shared pool since the objects are always the same, I think we do not need to synchronize, please shed some lights on this. Thanks
public class WeakPool<T> {
private final WeakHashMap<T, WeakReference<T>> pool = new WeakHashMap<T, WeakReference<T>>();
public T get(T object) {
final T res;
WeakReference<T> ref = pool.get(object);
if (ref != null) {
res = ref.get();
} else {
res = null;
}
return res;
}
public void put(T object) {
pool.put(object, new WeakReference<T>(object));
}
}
public class InternPool<T> {
private final WeakPool<T> pool = new WeakPool<T>();
public synchronized T intern(T object) {
T res = pool.get(object);
if (res == null) {
pool.put(object);
res = object;
}
return res;
}
}
Here is the code from this post: Generic InternPool<T> in Java?
The question is do we need synchronized on this intern method?