【问题标题】:Asking about threading, arrays and cache memory询问线程、数组和缓存内存
【发布时间】:2010-11-26 09:43:24
【问题描述】:

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

 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 是基于数据文件的一些分隔符的分割线。文件可以是任意大小。

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

【问题讨论】:

  • 你的单例不是线程安全的。
  • 使用101010按钮格式化代码sn-p
  • 不鼓励使用ThreadLocal(参见 Effective Java 2nd...)。
  • @khachik:抱歉,第一次预览的格式很好。现在?
  • @PartlyClody: TreadLocal 不应该是保持线程会话对象之间距离的容器吗?

标签: java oop list synchronized thread-local


【解决方案1】:

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

【讨论】:

  • 能否用自然的方式描述,这段代码有什么问题?我假设至少是单例,因为单例应该没问题。
  • 所以之后的事情变得古怪。然而,在文档中,向量本身是同步的......所以我不应该安全地使用“tread-session”加载同步类吗?
猜你喜欢
  • 1970-01-01
  • 2013-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-01
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多