KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openlaszlo > cache > PersistentMap


1 /******************************************************************************
2  * PersistentMap.java
3  *****************************************************************************/

4
5 /* J_LZ_COPYRIGHT_BEGIN *******************************************************
6 * Copyright 2001-2004 Laszlo Systems, Inc. All Rights Reserved. *
7 * Use is subject to license terms. *
8 * J_LZ_COPYRIGHT_END *********************************************************/

9
10
11 package org.openlaszlo.cache;
12 import java.io.*;
13 import java.util.*;
14
15 /** This class implements a subset of java.util.AbstractMap semantics,
16     persisted to the file named by cacheDirectory. */

17 public class PersistentMap extends Cache {
18     protected final Map map = new HashMap();
19     
20     public PersistentMap(String JavaDoc name, File cacheDirectory, Properties props)
21         throws IOException
22     {
23         super(name, cacheDirectory, props);
24     }
25     
26     public Object JavaDoc get(Serializable key) {
27         Object JavaDoc value = this.map.get(key);
28         if (value != null)
29             return value;
30         Item item = this.getItem(key);
31         if (item == null)
32             return null;
33         InputStream is = item.getStream();
34         try {
35             value = new ObjectInputStream(is).readObject();
36         } catch (ClassNotFoundException JavaDoc e) {
37             return null;
38         } catch (IOException e) {
39             return null;
40         } finally {
41             try {
42                 is.close();
43             } catch (IOException e) {}
44         }
45         this.map.put(key, value);
46         return value;
47     }
48     
49     public void put(Serializable key, final Serializable value) {
50         this.map.put(key, value);
51         try {
52             Item item = this.findItem(key, null, false);
53             PipedInputStream is = new PipedInputStream();
54             final PipedOutputStream os = new PipedOutputStream();
55             is.connect(os);
56             new Thread JavaDoc() {
57                 public void run() {
58                     try {
59                         ObjectOutputStream oos = new ObjectOutputStream(os);
60                         oos.writeObject(value);
61                         oos.close();
62                     } catch (IOException e) {
63                         throw new RuntimeException JavaDoc(e);
64                     }
65                 }
66             }.start();
67             item.update(is, null);
68             item.updateInfo();
69             item.markClean();
70         } catch (java.io.IOException JavaDoc e) {
71             throw new RuntimeException JavaDoc(e);
72         }
73     }
74 }
75
Popular Tags