/* Timestamp format */ privatefinal String format;
/* Number of cached entries */ privatefinalint cacheSize;
privatefinal Cache cache;
/** *Replacethemillisecondformattingcharacter'S'bysomedummycharactersinordertomaketheresulting *formattedtimestampscacheable.Ourconsumermightchoosetoreplacethedummycharswiththeactual *millisecondsbecausethat'srelativelycheap.
*/ private String tidyFormat(String format) { boolean escape = false;
StringBuilder result = new StringBuilder(); int len = format.length(); char x; for (int i = 0; i < len; i++) {
x = format.charAt(i); if (escape || x != 'S') {
result.append(x);
} else {
result.append(MSEC_PATTERN);
} if (x == '\'') {
escape = !escape;
}
} return result.toString();
}
public DateFormatCache(int size, String format, DateFormatCache parent) {
cacheSize = size; this.format = tidyFormat(format);
Cache parentCache = null; if (parent != null) { synchronized (parent) {
parentCache = parent.cache;
}
}
cache = new Cache(parentCache);
}
public String getFormat(long time) { return cache.getFormat(time);
}
public String getTimeFormat() { return format;
}
privateclass Cache {
/* Second formatted in most recent invocation */ privatelong previousSeconds = Long.MIN_VALUE; /* Formatted timestamp generated in most recent invocation */ private String previousFormat = "";
/* First second contained in cache */ privatelong first = Long.MIN_VALUE; /* Last second contained in cache */ privatelong last = Long.MIN_VALUE; /* Index of "first" in the cyclic cache */ privateint offset = 0; /* Helper object to be able to call SimpleDateFormat.format(). */ privatefinal Date currentDate = new Date();
/* Second step: Try to locate in cache */
previousSeconds = seconds; int index = (offset + (int) (seconds - first)) % cacheSize; if (index < 0) {
index += cacheSize;
} if (seconds >= first && seconds <= last) { if (cache[index] != null) { /* Found, so remember for next call and return. */
previousFormat = cache[index]; return previousFormat;
}
/* Third step: not found in cache, adjust cache and add item */
} elseif (seconds >= last + cacheSize || seconds <= first - cacheSize) {
first = seconds;
last = first + cacheSize - 1;
index = 0;
offset = 0; for (int i = 1; i < cacheSize; i++) {
cache[i] = null;
}
} elseif (seconds > last) { for (int i = 1; i < seconds - last; i++) {
cache[(index + cacheSize - i) % cacheSize] = null;
}
first = seconds - (cacheSize - 1);
last = seconds;
offset = (index + 1) % cacheSize;
} elseif (seconds < first) { for (int i = 1; i < first - seconds; i++) {
cache[(index + i) % cacheSize] = null;
}
first = seconds;
last = seconds + (cacheSize - 1);
offset = index;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.