summaryrefslogtreecommitdiff
path: root/java/src/IceUtil/Cache.java
blob: feb7a789b53c35e2a038627245120c86ff52cbec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// **********************************************************************
//
// Copyright (c) 2004
// ZeroC, Inc.
// Billerica, MA, USA
//
// All Rights Reserved.
//
// Ice is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License version 2 as published by
// the Free Software Foundation.
//
// **********************************************************************

package IceUtil;

//
// An abstraction to efficiently populate a Cache, without holding
// a lock while loading from a database.
//
// TODO: implement efficiently!
//

public class Cache
{
    public Cache(Store store)
    {
	_store = store;
    }
    
    public Object 
    getIfPinned(Object key)
    {
	synchronized(_map)
	{
	    return _map.get(key);
	}
    }
    
    public Object
    pin(Object key)
    {
	synchronized(_map)
	{
	    Object o = _map.get(key);
	    if(o == null)
	    {
		o = _store.load(key);
		if(o != null)
		{
		    _map.put(key, o);
		}
	    }
	    return o;
	}
    }

    public Object
    unpin(Object key)
    {
	synchronized(_map)
	{
	    return _map.remove(key);
	}
    }

    public void
    clear()
    {
	synchronized(_map)
	{
	    _map.clear();
	}
    }
    
    public int
    size()
    {
	synchronized(_map)
	{
	    return _map.size();
	}
    }

    public Object
    add(Object key, Object value)
    {
	assert value != null;

	synchronized(_map)
	{
	    Object existingVal = _map.put(key, value);
	    if(existingVal != null)
	    {
		_map.put(key, existingVal);
		return existingVal;
	    }
	    
	    //
	    // Let's check if it's in the store
	    //
	    existingVal = _store.load(key);
	    if(existingVal != null)
	    {
		_map.put(key, existingVal);
		return existingVal;
	    }
	    else
	    {
		return null;
	    }
	}
    }

    public Object
    pin(Object key, Object value)
    {
	synchronized(_map)
	{
	    Object existingVal = _map.put(key, value);
	    if(existingVal != null)
	    {
		_map.put(key, existingVal);
	    }
	    return existingVal;
	}
    }

    private final java.util.Map _map = new java.util.HashMap();
    private final Store _store;

}