KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > cache > interceptors > BaseCacheLoaderInterceptor


1 /*
2  * JBoss, Home of Professional Open Source
3  *
4  * Distributable under LGPL license.
5  * See terms of license at gnu.org.
6  */

7 package org.jboss.cache.interceptors;
8
9 import org.jboss.cache.CacheSPI;
10 import org.jboss.cache.loader.CacheLoader;
11
12 import java.util.ConcurrentModificationException JavaDoc;
13 import java.util.Iterator JavaDoc;
14 import java.util.List JavaDoc;
15 import java.util.Map JavaDoc;
16 import java.util.concurrent.ConcurrentHashMap JavaDoc;
17
18 /**
19  * asbtract superclass for cache loader and cache store interceptors.
20  *
21  * @author <a HREF="mailto:manik@jboss.org">Manik Surtani (manik@jboss.org)</a>
22  */

23 public class BaseCacheLoaderInterceptor extends Interceptor
24 {
25    protected CacheLoader loader = null;
26    private Map JavaDoc lockMap = new ConcurrentHashMap JavaDoc();
27
28    public void setCache(CacheSPI cache)
29    {
30       super.setCache(cache);
31       this.loader = cache.getCacheLoaderManager().getCacheLoader();
32    }
33
34    /**
35     * Simplistic locking mechanism that uses a single synchronized lock per
36     * fqn accessed. Nothing complex here - no isolation levels or
37     * consideration for the operation being performed for now.
38     */

39    protected void obtainLoaderLock(Object JavaDoc lock) throws InterruptedException JavaDoc
40    {
41       Thread JavaDoc current = Thread.currentThread();
42
43       synchronized (this)
44       {
45          while (lockMap.containsKey(lock) && !lockMap.get(lock).equals(current))
46          {
47             // someone else owns the lock. Wait for it.
48
this.wait();
49          }
50
51          if (lockMap.containsKey(lock) && !lockMap.get(lock).equals(current))
52          {
53             throw new ConcurrentModificationException JavaDoc("Loader lock " + lock + " is already held by someone else.");
54          }
55
56          lockMap.put(lock, current);
57       }
58    }
59
60    /**
61     * Releases simplistic loader lock.
62     */

63    protected void releaseLoaderLock(Object JavaDoc lock)
64    {
65       synchronized (this)
66       {
67          lockMap.remove(lock);
68          this.notify();
69       }
70    }
71
72    protected void releaseLoaderLocks(List JavaDoc locks)
73    {
74       Iterator JavaDoc it = locks.iterator();
75       while (it.hasNext())
76       {
77          releaseLoaderLock(it.next());
78       }
79    }
80
81    protected void obtainLoaderLocks(List JavaDoc locks) throws InterruptedException JavaDoc
82    {
83       Iterator JavaDoc it = locks.iterator();
84       while (it.hasNext())
85       {
86          obtainLoaderLock(it.next());
87       }
88    }
89 }
90
Popular Tags