【发布时间】: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