01: /*
02: * Copyright (C) 2007 XStream Committers.
03: * All rights reserved.
04: *
05: * The software in this package is published under the terms of the BSD
06: * style license a copy of which has been included with this distribution in
07: * the LICENSE.txt file.
08: *
09: * Created on 04. May 2007 by Joerg Schaible
10: */
11: package com.thoughtworks.xstream.benchmark.strings.products;
12:
13: import com.thoughtworks.xstream.XStream;
14: import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
15: import com.thoughtworks.xstream.io.xml.XppDriver;
16: import com.thoughtworks.xstream.tools.benchmark.Product;
17:
18: import java.io.InputStream;
19: import java.io.OutputStream;
20: import java.util.Map;
21: import java.util.WeakHashMap;
22: import java.lang.ref.WeakReference;
23:
24: /**
25: * Uses WeakHashMap for StringConverter.
26: *
27: * @author Jörg Schaible
28: * @see com.thoughtworks.xstream.tools.benchmark.Harness
29: * @see Product
30: */
31: public class StringWithWeakHashMapConverter implements Product {
32:
33: private final XStream xstream;
34:
35: public StringWithWeakHashMapConverter() {
36: xstream = new XStream(new XppDriver());
37: xstream.registerConverter(new StringConverter());
38: }
39:
40: public void serialize(Object object, OutputStream output)
41: throws Exception {
42: xstream.toXML(object, output);
43: }
44:
45: public Object deserialize(InputStream input) throws Exception {
46: return xstream.fromXML(input);
47: }
48:
49: public String toString() {
50: return "StringConverter using WeakHashMap";
51: }
52:
53: /**
54: * Converts a String to a String.
55: * <p>
56: * Well ok, it doesn't <i>actually</i> do any conversion. The converter uses a map to reuse
57: * instances. This map is by default a {@link WeakHashMap}.
58: * </p>
59: *
60: * @author Rene Schwietzke
61: * @author Jörg Schaible
62: * @see WeakHashMap
63: */
64: public static class StringConverter extends
65: AbstractSingleValueConverter {
66: /**
67: * A Map to store strings as long as needed to map similar strings onto the same
68: * instance and conserve memory. The map can be set from the outside during
69: * construction, so it can be a LRU map or a weak map, sychronized or not.
70: */
71: private final Map cache;
72:
73: public StringConverter(Map map) {
74: this .cache = map;
75: }
76:
77: public StringConverter() {
78: this (new WeakHashMap());
79: }
80:
81: public boolean canConvert(Class type) {
82: return type.equals(String.class);
83: }
84:
85: public Object fromString(String str) {
86: WeakReference ref = (WeakReference) cache.get(str);
87: String s = (String) (ref == null ? null : ref.get());
88:
89: if (s == null) {
90: // fill cache
91: cache.put(str, new WeakReference(str));
92:
93: s = str;
94: }
95:
96: return s;
97: }
98: }
99: }
|