0

我希望以一种好的方式:-) 我写了这段代码。我想做的是构建类似“缓存”的东西。我假设我必须注意不同的线程,因为可能有很多调用会到达那个类,所以我尝试了 ThreadLocal 功能。基本模式是有“许多向量集”向量包含如下内容: VECTOR.FieldName = "X" VECTOR.FieldValue= "Y" 集合中有这么多向量对象。针对来自不同机器、用户、对象的不同调用的不同设置。

 private static CacheVector instance = null;
        private static SortedSet<SplittingVector> s = null;
        private static TreeSet<SplittingVector> t = null;
        private static ThreadLocal<SortedSet<SplittingVector>> setOfVectors = new ThreadLocal<SortedSet<SplittingVector>>();

        private static class MyComparator implements Comparator<SplittingVector> {
     public int compare(SplittingVector a, SplittingVector b) {
         return 1;
     }
     // No need to override equals.
        }

        private CacheVector() {
        }

        public static SortedSet<SplittingVector> getInstance(SplittingVector vector) {
     if (instance == null) {
         instance = new CacheVector();
         //TreeSet<SplittingVector>
         t = new TreeSet<SplittingVector>(new MyComparator());
         t.add(vector);
         s = Collections.synchronizedSortedSet(t);//Sort the set of vectors
         CacheVector.assign(s);
     } else {
         //TreeSet<SplittingVector> t = new TreeSet<SplittingVector>();
         t.add(vector);
         s = Collections.synchronizedSortedSet(t);//Sort the set of vectors
         CacheVector.assign(s);
     }
     return CacheVector.setOfVectors.get();
        }

        public SortedSet<SplittingVector> retrieve() throws Exception {
     SortedSet<SplittingVector> set = setOfVectors.get();
     if (set == null) {
         throw new Exception("SET IS EMPTY");
     }
     return set;
        }

        private static void assign(SortedSet<SplittingVector> nSet) {
     CacheVector.setOfVectors.set(nSet);
        }

所以......我在附件中有它,我像这样使用它:

CachedVector cache = CachedVector.getInstance(bufferedline);

好的部分:Bufferedline 是基于数据文件的一些分隔符的分割线。文件可以是任意大小。

那么你怎么看这段代码呢?我应该担心吗?对于这条消息的大小,我深表歉意!

4

1 回答 1

0

编写正确的多线程代码并不是那么容易(即您的单例无法做到),因此如果可能,请尝试依赖现有的解决方案。如果您正在寻找 Java 中的线程安全 Cache 实现,请查看此LinkedHashMap。您可以使用它来实现LRU 缓存。和collections.synchronizedMap()。可以使这个线程安全。

于 2010-11-26T09:51:59.920 回答