我希望以一种好的方式:-) 我写了这段代码。我想做的是构建类似“缓存”的东西。我假设我必须注意不同的线程,因为可能有很多调用会到达那个类,所以我尝试了 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 是基于数据文件的一些分隔符的分割线。文件可以是任意大小。
那么你怎么看这段代码呢?我应该担心吗?对于这条消息的大小,我深表歉意!