/*
 * Copyright (C) 2005 Joe Walnes.
 * Copyright (C) 2006, 2007 XStream Committers.
 * All rights reserved.
 *
 * The software in this package is published under the terms of the BSD
 * style license a copy of which has been included with this distribution in
 * the LICENSE.txt file.
 * 
 * Created on 22. January 2005 by Joe Walnes
 */
package com.thoughtworks.xstream.mapper;

import com.thoughtworks.xstream.alias.ClassMapper;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Mapper that caches which names map to which classes. Prevents repetitive searching and class loading.
 *
 * @author Joe Walnes
 */
public class CachingMapper extends MapperWrapper {

    private transient Map cache = Collections.synchronizedMap(new HashMap());

    public CachingMapper(Mapper wrapped) {
        super(wrapped);
    }

    /**
     * @deprecated As of 1.2, use {@link #CachingMapper(Mapper)}
     */
    public CachingMapper(ClassMapper wrapped) {
        this((Mapper)wrapped);
    }

    public Class realClass(String elementName) {
        Class cached = (Class) cache.get(elementName);
        if (cached != null) {
            return cached;
        } else {
            Class result = super.realClass(elementName);
            cache.put(elementName, result);
            return result;
        }
    }
    
    private Object readResolve() {
        cache = Collections.synchronizedMap(new HashMap());
        return this;
    }

}

@@ -57,16 +57,22 @@
 06, 2007
+, 2008
  XStream
@@ -428,24 +428,60 @@
 assMapper;%0A%0A
+import java.lang.ref.WeakReference;%0A
 import java.
@@ -545,16 +545,46 @@
 til.Map;
+%0Aimport java.util.WeakHashMap;
 %0A%0A/**%0A *
@@ -797,58 +797,22 @@
 Map 
-cache = Collections.synchronizedMap(new HashMap())
+realClassCache
 ;%0A%0A 
@@ -869,32 +869,55 @@
 super(wrapped);%0A
+        readResolve();%0A
     %7D%0A%0A    /**%0A 
@@ -1063,24 +1063,47 @@
 r)wrapped);%0A
+        readResolve();%0A
     %7D%0A%0A    p
@@ -1158,32 +1158,60 @@
     
-Class cached = (
+WeakReference reference = (WeakReference) real
 Class
-) c
+C
 ache
@@ -1221,32 +1221,121 @@
 t(elementName);%0A
+        if (reference != null) %7B%0A            Class cached = (Class) reference.get();%0A    
         if (cach
@@ -1340,32 +1340,36 @@
 ched != null) %7B%0A
+    
             retu
@@ -1391,16 +1391,23 @@
     
-%7D else %7B
+    %7D%0A        %7D
 %0A   
@@ -1403,32 +1403,37 @@
       %7D%0A        
+%0A    
     Class result
@@ -1469,29 +1469,34 @@
 e);%0A        
-    c
+realClassC
 ache.put(ele
@@ -1509,15 +1509,34 @@
 me, 
+new WeakReference(
 result)
+)
 ;%0A  
@@ -1537,28 +1537,24 @@
 ));%0A        
- 
-   
 return resul
@@ -1560,28 +1560,14 @@
 lt;%0A
-        %7D%0A
     %7D%0A
-    
 %0A   
@@ -1606,17 +1606,26 @@
         
-c
+realClassC
 ache = C
@@ -1663,16 +1663,19 @@
 HashMap(
+128
 ));%0A    

Use WeakReference to allow garbage collection of the class loader (XSTR-462).