01: /*
02: * Copyright (C) 2003, 2004, 2005 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 26. September 2003 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.converters.basic;
13:
14: import java.lang.ref.WeakReference;
15: import java.util.Collections;
16: import java.util.Map;
17: import java.util.WeakHashMap;
18:
19: /**
20: * Converts a String to a String ;).
21: * <p>
22: * Well ok, it doesn't <i>actually</i> do any conversion. The converter uses a map to reuse instances. This map is by
23: * default a synchronized {@link WeakHashMap}.
24: * </p>
25: *
26: * @author Joe Walnes
27: * @author Rene Schwietzke
28: * @author Jörg Schaible
29: * @see String#intern()
30: */
31: public class StringConverter extends AbstractSingleValueConverter {
32:
33: /**
34: * A Map to store strings as long as needed to map similar strings onto the same instance and conserve memory. The
35: * map can be set from the outside during construction, so it can be a LRU map or a weak map, synchronised or not.
36: */
37: private final Map cache;
38:
39: public StringConverter(final Map map) {
40: cache = map;
41: }
42:
43: public StringConverter() {
44: this (Collections.synchronizedMap(new WeakHashMap()));
45: }
46:
47: public boolean canConvert(final Class type) {
48: return type.equals(String.class);
49: }
50:
51: public Object fromString(final String str) {
52: final WeakReference ref = (WeakReference) cache.get(str);
53: String s = (String) (ref == null ? null : ref.get());
54:
55: if (s == null) {
56: // fill cache
57: cache.put(str, new WeakReference(str));
58:
59: s = str;
60: }
61:
62: return s;
63: }
64: }
|