Generic InternPool in Java?

后端 未结 6 1158
天涯浪人
天涯浪人 2021-01-12 01:04

How would I write a generic InternPool in Java? Does it need a Internable interface?

String in Java has interning cap

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-12 01:44

    I would separate the solution into two classes to have cleaner code and also this way getting rid of loop:

    public class WeakPool {
        private final WeakHashMap> pool = new WeakHashMap>();
        public T get(T object) {
            final T res;
            WeakReference 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(object));
        }
    }
    

    and the interning class using the weak pool is very simple:

    public class InternPool {
    
        private final WeakPool pool = new WeakPool();
    
        public synchronized T intern(T object) {
            T res = pool.get(object);
            if (res == null) {
                pool.put(object);
                res = object;
            }
            return res;
        }
    }
    

提交回复
热议问题