001// Copyright 2004, 2005 The Apache Software Foundation 002// 003// Licensed under the Apache License, Version 2.0 (the "License"); 004// you may not use this file except in compliance with the License. 005// You may obtain a copy of the License at 006// 007// http://www.apache.org/licenses/LICENSE-2.0 008// 009// Unless required by applicable law or agreed to in writing, software 010// distributed under the License is distributed on an "AS IS" BASIS, 011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012// See the License for the specific language governing permissions and 013// limitations under the License. 014 015package org.apache.tapestry.services.impl; 016 017import java.util.HashMap; 018import java.util.Iterator; 019import java.util.LinkedList; 020import java.util.List; 021import java.util.Map; 022 023import org.apache.tapestry.event.ReportStatusEvent; 024import org.apache.tapestry.event.ReportStatusListener; 025import org.apache.tapestry.event.ResetEventListener; 026import org.apache.tapestry.services.ObjectPool; 027 028/** 029 * Implementation of the {@link org.apache.tapestry.services.ObjectPool} interface. 030 * <p> 031 * This ia a minimal implementation, one that has no concept of automatically removing unused pooled 032 * objects. Eventually, it will also register for notifications about general cache cleaning. 033 * 034 * @author Howard Lewis Ship 035 * @since 4.0 036 */ 037public class ObjectPoolImpl implements ObjectPool, ResetEventListener, ReportStatusListener 038{ 039 private String _serviceId; 040 041 private int _count = 0; 042 043 /** 044 * Pool of Lists (of pooled objects), keyed on arbitrary key. 045 */ 046 private Map _pool = new HashMap(); 047 048 public synchronized Object get(Object key) 049 { 050 List pooled = (List) _pool.get(key); 051 052 if (pooled == null || pooled.isEmpty()) 053 return null; 054 055 _count--; 056 057 return pooled.remove(0); 058 } 059 060 public synchronized void store(Object key, Object value) 061 { 062 List pooled = (List) _pool.get(key); 063 064 if (pooled == null) 065 { 066 pooled = new LinkedList(); 067 _pool.put(key, pooled); 068 } 069 070 pooled.add(value); 071 072 _count++; 073 } 074 075 public synchronized void resetEventDidOccur() 076 { 077 _pool.clear(); 078 079 _count = 0; 080 } 081 082 public synchronized void reportStatus(ReportStatusEvent event) 083 { 084 event.title(_serviceId); 085 086 event.property("total count", _count); 087 088 event.section("Count by Key"); 089 090 Iterator i = _pool.entrySet().iterator(); 091 092 while (i.hasNext()) 093 { 094 Map.Entry entry = (Map.Entry) i.next(); 095 096 String key = entry.getKey().toString(); 097 098 List pooled = (List) entry.getValue(); 099 100 event.property(key, pooled.size()); 101 } 102 } 103 104 public void setServiceId(String serviceId) 105 { 106 _serviceId = serviceId; 107 } 108 109}