1 package org.apache.commons.jcs.engine.control;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Iterator;
27 import java.util.Map;
28 import java.util.Set;
29 import java.util.concurrent.ScheduledExecutorService;
30 import java.util.concurrent.ScheduledFuture;
31 import java.util.concurrent.TimeUnit;
32 import java.util.concurrent.atomic.AtomicBoolean;
33 import java.util.concurrent.atomic.AtomicInteger;
34
35 import org.apache.commons.jcs.access.exception.CacheException;
36 import org.apache.commons.jcs.access.exception.ObjectNotFoundException;
37 import org.apache.commons.jcs.auxiliary.AuxiliaryCache;
38 import org.apache.commons.jcs.engine.CacheConstants;
39 import org.apache.commons.jcs.engine.CacheStatus;
40 import org.apache.commons.jcs.engine.behavior.ICache;
41 import org.apache.commons.jcs.engine.behavior.ICacheElement;
42 import org.apache.commons.jcs.engine.behavior.ICompositeCacheAttributes;
43 import org.apache.commons.jcs.engine.behavior.ICompositeCacheAttributes.DiskUsagePattern;
44 import org.apache.commons.jcs.engine.behavior.IElementAttributes;
45 import org.apache.commons.jcs.engine.behavior.IRequireScheduler;
46 import org.apache.commons.jcs.engine.control.event.ElementEvent;
47 import org.apache.commons.jcs.engine.control.event.behavior.ElementEventType;
48 import org.apache.commons.jcs.engine.control.event.behavior.IElementEvent;
49 import org.apache.commons.jcs.engine.control.event.behavior.IElementEventHandler;
50 import org.apache.commons.jcs.engine.control.event.behavior.IElementEventQueue;
51 import org.apache.commons.jcs.engine.control.group.GroupId;
52 import org.apache.commons.jcs.engine.match.KeyMatcherPatternImpl;
53 import org.apache.commons.jcs.engine.match.behavior.IKeyMatcher;
54 import org.apache.commons.jcs.engine.memory.behavior.IMemoryCache;
55 import org.apache.commons.jcs.engine.memory.lru.LRUMemoryCache;
56 import org.apache.commons.jcs.engine.memory.shrinking.ShrinkerThread;
57 import org.apache.commons.jcs.engine.stats.CacheStats;
58 import org.apache.commons.jcs.engine.stats.StatElement;
59 import org.apache.commons.jcs.engine.stats.behavior.ICacheStats;
60 import org.apache.commons.jcs.engine.stats.behavior.IStatElement;
61 import org.apache.commons.jcs.engine.stats.behavior.IStats;
62 import org.apache.commons.logging.Log;
63 import org.apache.commons.logging.LogFactory;
64
65
66
67
68
69
70
71 public class CompositeCache<K, V>
72 implements ICache<K, V>, IRequireScheduler
73 {
74
75 private static final Log log = LogFactory.getLog( CompositeCache.class );
76
77
78
79
80
81 private IElementEventQueue elementEventQ;
82
83
84 @SuppressWarnings("unchecked")
85 private AuxiliaryCache<K, V>[] auxCaches = new AuxiliaryCache[0];
86
87
88 private AtomicBoolean alive;
89
90
91 private IElementAttributes attr;
92
93
94 private ICompositeCacheAttributes cacheAttr;
95
96
97 private AtomicInteger updateCount;
98
99
100 private AtomicInteger removeCount;
101
102
103 private AtomicInteger hitCountRam;
104
105
106 private AtomicInteger hitCountAux;
107
108
109 private AtomicInteger missCountNotFound;
110
111
112 private AtomicInteger missCountExpired;
113
114
115 private CompositeCacheManager cacheManager = null;
116
117
118
119
120
121 private IMemoryCache<K, V> memCache;
122
123
124 private IKeyMatcher<K> keyMatcher = new KeyMatcherPatternImpl<K>();
125
126 private ScheduledFuture<?> future;
127
128
129
130
131
132
133
134 public CompositeCache( ICompositeCacheAttributes cattr, IElementAttributes attr )
135 {
136 this.attr = attr;
137 this.cacheAttr = cattr;
138 this.alive = new AtomicBoolean(true);
139 this.updateCount = new AtomicInteger(0);
140 this.removeCount = new AtomicInteger(0);
141 this.hitCountRam = new AtomicInteger(0);
142 this.hitCountAux = new AtomicInteger(0);
143 this.missCountNotFound = new AtomicInteger(0);
144 this.missCountExpired = new AtomicInteger(0);
145
146 createMemoryCache( cattr );
147
148 if ( log.isInfoEnabled() )
149 {
150 log.info( "Constructed cache with name [" + cacheAttr.getCacheName() + "] and cache attributes " + cattr );
151 }
152 }
153
154
155
156
157
158
159 public void setElementEventQueue( IElementEventQueue queue )
160 {
161 this.elementEventQ = queue;
162 }
163
164
165
166
167
168
169 public void setCompositeCacheManager( CompositeCacheManager manager )
170 {
171 this.cacheManager = manager;
172 }
173
174
175
176
177 @Override
178 public void setScheduledExecutorService(ScheduledExecutorService scheduledExecutor)
179 {
180 if ( cacheAttr.isUseMemoryShrinker() )
181 {
182 future = scheduledExecutor.scheduleAtFixedRate(
183 new ShrinkerThread<K, V>(this), 0, cacheAttr.getShrinkerIntervalSeconds(),
184 TimeUnit.SECONDS);
185 }
186 }
187
188
189
190
191
192
193 public void setAuxCaches( AuxiliaryCache<K, V>[] auxCaches )
194 {
195 this.auxCaches = auxCaches;
196 }
197
198
199
200
201
202
203 public AuxiliaryCache<K, V>[] getAuxCaches()
204 {
205 return this.auxCaches;
206 }
207
208
209
210
211
212
213
214 @Override
215 public void update( ICacheElement<K, V> ce )
216 throws IOException
217 {
218 update( ce, false );
219 }
220
221
222
223
224
225
226
227 public void localUpdate( ICacheElement<K, V> ce )
228 throws IOException
229 {
230 update( ce, true );
231 }
232
233
234
235
236
237
238
239
240
241 protected void update( ICacheElement<K, V> cacheElement, boolean localOnly )
242 throws IOException
243 {
244
245 if ( cacheElement.getKey() instanceof String
246 && cacheElement.getKey().toString().endsWith( CacheConstants.NAME_COMPONENT_DELIMITER ) )
247 {
248 throw new IllegalArgumentException( "key must not end with " + CacheConstants.NAME_COMPONENT_DELIMITER
249 + " for a put operation" );
250 }
251 else if ( cacheElement.getKey() instanceof GroupId )
252 {
253 throw new IllegalArgumentException( "key cannot be a GroupId " + " for a put operation" );
254 }
255
256 if ( log.isDebugEnabled() )
257 {
258 log.debug( "Updating memory cache " + cacheElement.getKey() );
259 }
260
261 updateCount.incrementAndGet();
262
263 synchronized ( this )
264 {
265 memCache.update( cacheElement );
266 updateAuxiliaries( cacheElement, localOnly );
267 }
268
269 cacheElement.getElementAttributes().setLastAccessTimeNow();
270 }
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289 protected void updateAuxiliaries( ICacheElement<K, V> cacheElement, boolean localOnly )
290 throws IOException
291 {
292
293
294
295
296
297 if ( log.isDebugEnabled() )
298 {
299 if ( auxCaches.length > 0 )
300 {
301 log.debug( "Updating auxiliary caches" );
302 }
303 else
304 {
305 log.debug( "No auxiliary cache to update" );
306 }
307 }
308
309 for ( ICache<K, V> aux : auxCaches )
310 {
311 if ( aux == null )
312 {
313 continue;
314 }
315
316 if ( log.isDebugEnabled() )
317 {
318 log.debug( "Auxiliary cache type: " + aux.getCacheType() );
319 }
320
321 switch (aux.getCacheType())
322 {
323
324 case REMOTE_CACHE:
325 if ( log.isDebugEnabled() )
326 {
327 log.debug( "ce.getElementAttributes().getIsRemote() = "
328 + cacheElement.getElementAttributes().getIsRemote() );
329 }
330
331 if ( cacheElement.getElementAttributes().getIsRemote() && !localOnly )
332 {
333 try
334 {
335
336
337 aux.update( cacheElement );
338 if ( log.isDebugEnabled() )
339 {
340 log.debug( "Updated remote store for " + cacheElement.getKey() + cacheElement );
341 }
342 }
343 catch ( IOException ex )
344 {
345 log.error( "Failure in updateExclude", ex );
346 }
347 }
348 break;
349
350
351 case LATERAL_CACHE:
352
353
354 if ( log.isDebugEnabled() )
355 {
356 log.debug( "lateralcache in aux list: cattr " + cacheAttr.isUseLateral() );
357 }
358 if ( cacheAttr.isUseLateral() && cacheElement.getElementAttributes().getIsLateral() && !localOnly )
359 {
360
361
362
363 aux.update( cacheElement );
364 if ( log.isDebugEnabled() )
365 {
366 log.debug( "updated lateral cache for " + cacheElement.getKey() );
367 }
368 }
369 break;
370
371
372 case DISK_CACHE:
373 if ( log.isDebugEnabled() )
374 {
375 log.debug( "diskcache in aux list: cattr " + cacheAttr.isUseDisk() );
376 }
377 if ( cacheAttr.isUseDisk()
378 && cacheAttr.getDiskUsagePattern() == DiskUsagePattern.UPDATE
379 && cacheElement.getElementAttributes().getIsSpool() )
380 {
381 aux.update( cacheElement );
382 if ( log.isDebugEnabled() )
383 {
384 log.debug( "updated disk cache for " + cacheElement.getKey() );
385 }
386 }
387 break;
388
389 default:
390 break;
391 }
392 }
393 }
394
395
396
397
398
399
400
401
402
403
404 public void spoolToDisk( ICacheElement<K, V> ce )
405 {
406
407 if ( !ce.getElementAttributes().getIsSpool() )
408 {
409
410 handleElementEvent( ce, ElementEventType.SPOOLED_NOT_ALLOWED );
411 return;
412 }
413
414 boolean diskAvailable = false;
415
416
417 for ( ICache<K, V> aux : auxCaches )
418 {
419 if ( aux != null && aux.getCacheType() == CacheType.DISK_CACHE )
420 {
421 diskAvailable = true;
422
423 if ( cacheAttr.getDiskUsagePattern() == DiskUsagePattern.SWAP )
424 {
425
426 try
427 {
428 handleElementEvent( ce, ElementEventType.SPOOLED_DISK_AVAILABLE );
429 aux.update( ce );
430 }
431 catch ( IOException ex )
432 {
433
434 log.error( "Problem spooling item to disk cache.", ex );
435 throw new IllegalStateException( ex.getMessage() );
436 }
437
438 if ( log.isDebugEnabled() )
439 {
440 log.debug( "spoolToDisk done for: " + ce.getKey() + " on disk cache[" + aux.getCacheName() + "]" );
441 }
442 }
443 else
444 {
445 if ( log.isDebugEnabled() )
446 {
447 log.debug( "DiskCache available, but JCS is not configured to use the DiskCache as a swap." );
448 }
449 }
450 }
451 }
452
453 if ( !diskAvailable )
454 {
455 try
456 {
457 handleElementEvent( ce, ElementEventType.SPOOLED_DISK_NOT_AVAILABLE );
458 }
459 catch ( Exception e )
460 {
461 log.error( "Trouble handling the ELEMENT_EVENT_SPOOLED_DISK_NOT_AVAILABLE element event", e );
462 }
463 }
464 }
465
466
467
468
469
470
471
472
473 @Override
474 public ICacheElement<K, V> get( K key )
475 {
476 return get( key, false );
477 }
478
479
480
481
482
483
484
485 public ICacheElement<K, V> localGet( K key )
486 {
487 return get( key, true );
488 }
489
490
491
492
493
494
495
496
497
498
499
500
501 protected ICacheElement<K, V> get( K key, boolean localOnly )
502 {
503 ICacheElement<K, V> element = null;
504
505 boolean found = false;
506
507 if ( log.isDebugEnabled() )
508 {
509 log.debug( "get: key = " + key + ", localOnly = " + localOnly );
510 }
511
512 synchronized (this)
513 {
514 try
515 {
516
517 element = memCache.get( key );
518
519 if ( element != null )
520 {
521
522 if ( isExpired( element ) )
523 {
524 if ( log.isDebugEnabled() )
525 {
526 log.debug( cacheAttr.getCacheName() + " - Memory cache hit, but element expired" );
527 }
528
529 doExpires(element);
530 element = null;
531 }
532 else
533 {
534 if ( log.isDebugEnabled() )
535 {
536 log.debug( cacheAttr.getCacheName() + " - Memory cache hit" );
537 }
538
539
540 hitCountRam.incrementAndGet();
541 }
542
543 found = true;
544 }
545 else
546 {
547
548
549 for (AuxiliaryCache<K, V> aux : auxCaches)
550 {
551 if ( aux != null )
552 {
553 CacheType cacheType = aux.getCacheType();
554
555 if ( !localOnly || cacheType == CacheType.DISK_CACHE )
556 {
557 if ( log.isDebugEnabled() )
558 {
559 log.debug( "Attempting to get from aux [" + aux.getCacheName() + "] which is of type: "
560 + cacheType );
561 }
562
563 try
564 {
565 element = aux.get( key );
566 }
567 catch ( IOException e )
568 {
569 log.error( "Error getting from aux", e );
570 }
571 }
572
573 if ( log.isDebugEnabled() )
574 {
575 log.debug( "Got CacheElement: " + element );
576 }
577
578
579 if ( element != null )
580 {
581 if ( isExpired( element ) )
582 {
583 if ( log.isDebugEnabled() )
584 {
585 log.debug( cacheAttr.getCacheName() + " - Aux cache[" + aux.getCacheName() + "] hit, but element expired." );
586 }
587
588
589
590
591
592 doExpires(element);
593 element = null;
594 }
595 else
596 {
597 if ( log.isDebugEnabled() )
598 {
599 log.debug( cacheAttr.getCacheName() + " - Aux cache[" + aux.getCacheName() + "] hit" );
600 }
601
602
603 hitCountAux.incrementAndGet();
604 copyAuxiliaryRetrievedItemToMemory( element );
605 }
606
607 found = true;
608
609 break;
610 }
611 }
612 }
613 }
614 }
615 catch ( IOException e )
616 {
617 log.error( "Problem encountered getting element.", e );
618 }
619 }
620
621 if ( !found )
622 {
623 missCountNotFound.incrementAndGet();
624
625 if ( log.isDebugEnabled() )
626 {
627 log.debug( cacheAttr.getCacheName() + " - Miss" );
628 }
629 }
630
631 if (element != null)
632 {
633 element.getElementAttributes().setLastAccessTimeNow();
634 }
635
636 return element;
637 }
638
639 protected void doExpires(ICacheElement<K, V> element) {
640 missCountExpired.incrementAndGet();
641 remove( element.getKey() );
642 }
643
644
645
646
647
648
649
650
651 @Override
652 public Map<K, ICacheElement<K, V>> getMultiple( Set<K> keys )
653 {
654 return getMultiple( keys, false );
655 }
656
657
658
659
660
661
662
663
664
665 public Map<K, ICacheElement<K, V>> localGetMultiple( Set<K> keys )
666 {
667 return getMultiple( keys, true );
668 }
669
670
671
672
673
674
675
676
677
678
679
680
681
682 protected Map<K, ICacheElement<K, V>> getMultiple( Set<K> keys, boolean localOnly )
683 {
684 Map<K, ICacheElement<K, V>> elements = new HashMap<K, ICacheElement<K, V>>();
685
686 if ( log.isDebugEnabled() )
687 {
688 log.debug( "get: key = " + keys + ", localOnly = " + localOnly );
689 }
690
691 try
692 {
693
694 elements.putAll( getMultipleFromMemory( keys ) );
695
696
697 if ( elements.size() != keys.size() )
698 {
699 Set<K> remainingKeys = pruneKeysFound( keys, elements );
700 elements.putAll( getMultipleFromAuxiliaryCaches( remainingKeys, localOnly ) );
701 }
702 }
703 catch ( IOException e )
704 {
705 log.error( "Problem encountered getting elements.", e );
706 }
707
708
709 if ( elements.size() != keys.size() )
710 {
711 missCountNotFound.addAndGet(keys.size() - elements.size());
712
713 if ( log.isDebugEnabled() )
714 {
715 log.debug( cacheAttr.getCacheName() + " - " + ( keys.size() - elements.size() ) + " Misses" );
716 }
717 }
718
719 return elements;
720 }
721
722
723
724
725
726
727
728
729 private Map<K, ICacheElement<K, V>> getMultipleFromMemory( Set<K> keys )
730 throws IOException
731 {
732 Map<K, ICacheElement<K, V>> elementsFromMemory = memCache.getMultiple( keys );
733
734 Iterator<ICacheElement<K, V>> elementFromMemoryIterator = new HashMap<K, ICacheElement<K, V>>( elementsFromMemory ).values().iterator();
735
736 while ( elementFromMemoryIterator.hasNext() )
737 {
738 ICacheElement<K, V> element = elementFromMemoryIterator.next();
739
740 if ( element != null )
741 {
742
743 if ( isExpired( element ) )
744 {
745 if ( log.isDebugEnabled() )
746 {
747 log.debug( cacheAttr.getCacheName() + " - Memory cache hit, but element expired" );
748 }
749
750 doExpires(element);
751 elementsFromMemory.remove( element.getKey() );
752 }
753 else
754 {
755 if ( log.isDebugEnabled() )
756 {
757 log.debug( cacheAttr.getCacheName() + " - Memory cache hit" );
758 }
759
760
761 hitCountRam.incrementAndGet();
762 }
763 }
764 }
765 return elementsFromMemory;
766 }
767
768
769
770
771
772
773
774
775
776 private Map<K, ICacheElement<K, V>> getMultipleFromAuxiliaryCaches( Set<K> keys, boolean localOnly )
777 throws IOException
778 {
779 Map<K, ICacheElement<K, V>> elements = new HashMap<K, ICacheElement<K, V>>();
780 Set<K> remainingKeys = new HashSet<K>( keys );
781
782 for ( AuxiliaryCache<K, V> aux : auxCaches )
783 {
784 if ( aux != null )
785 {
786 Map<K, ICacheElement<K, V>> elementsFromAuxiliary =
787 new HashMap<K, ICacheElement<K, V>>();
788
789 CacheType cacheType = aux.getCacheType();
790
791 if ( !localOnly || cacheType == CacheType.DISK_CACHE )
792 {
793 if ( log.isDebugEnabled() )
794 {
795 log.debug( "Attempting to get from aux [" + aux.getCacheName() + "] which is of type: "
796 + cacheType );
797 }
798
799 try
800 {
801 elementsFromAuxiliary.putAll( aux.getMultiple( remainingKeys ) );
802 }
803 catch ( IOException e )
804 {
805 log.error( "Error getting from aux", e );
806 }
807 }
808
809 if ( log.isDebugEnabled() )
810 {
811 log.debug( "Got CacheElements: " + elementsFromAuxiliary );
812 }
813
814 processRetrievedElements( aux, elementsFromAuxiliary );
815
816 elements.putAll( elementsFromAuxiliary );
817
818 if ( elements.size() == keys.size() )
819 {
820 break;
821 }
822 else
823 {
824 remainingKeys = pruneKeysFound( keys, elements );
825 }
826 }
827 }
828
829 return elements;
830 }
831
832
833
834
835
836
837
838
839 @Override
840 public Map<K, ICacheElement<K, V>> getMatching( String pattern )
841 {
842 return getMatching( pattern, false );
843 }
844
845
846
847
848
849
850
851
852
853 public Map<K, ICacheElement<K, V>> localGetMatching( String pattern )
854 {
855 return getMatching( pattern, true );
856 }
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871 protected Map<K, ICacheElement<K, V>> getMatching( String pattern, boolean localOnly )
872 {
873 Map<K, ICacheElement<K, V>> elements = new HashMap<K, ICacheElement<K, V>>();
874
875 if ( log.isDebugEnabled() )
876 {
877 log.debug( "get: pattern [" + pattern + "], localOnly = " + localOnly );
878 }
879
880 try
881 {
882
883 elements.putAll( getMatchingFromAuxiliaryCaches( pattern, localOnly ) );
884
885
886 elements.putAll( getMatchingFromMemory( pattern ) );
887 }
888 catch ( Exception e )
889 {
890 log.error( "Problem encountered getting elements.", e );
891 }
892
893 return elements;
894 }
895
896
897
898
899
900
901
902
903
904
905 protected Map<K, ICacheElement<K, V>> getMatchingFromMemory( String pattern )
906 throws IOException
907 {
908
909
910 Set<K> keyArray = memCache.getKeySet();
911
912 Set<K> matchingKeys = getKeyMatcher().getMatchingKeysFromArray( pattern, keyArray );
913
914
915 return getMultipleFromMemory( matchingKeys );
916 }
917
918
919
920
921
922
923
924
925
926
927
928
929
930 private Map<K, ICacheElement<K, V>> getMatchingFromAuxiliaryCaches( String pattern, boolean localOnly )
931 throws IOException
932 {
933 Map<K, ICacheElement<K, V>> elements = new HashMap<K, ICacheElement<K, V>>();
934
935 for ( int i = auxCaches.length - 1; i >= 0; i-- )
936 {
937 AuxiliaryCache<K, V> aux = auxCaches[i];
938
939 if ( aux != null )
940 {
941 Map<K, ICacheElement<K, V>> elementsFromAuxiliary =
942 new HashMap<K, ICacheElement<K, V>>();
943
944 CacheType cacheType = aux.getCacheType();
945
946 if ( !localOnly || cacheType == CacheType.DISK_CACHE )
947 {
948 if ( log.isDebugEnabled() )
949 {
950 log.debug( "Attempting to get from aux [" + aux.getCacheName() + "] which is of type: "
951 + cacheType );
952 }
953
954 try
955 {
956 elementsFromAuxiliary.putAll( aux.getMatching( pattern ) );
957 }
958 catch ( IOException e )
959 {
960 log.error( "Error getting from aux", e );
961 }
962
963 if ( log.isDebugEnabled() )
964 {
965 log.debug( "Got CacheElements: " + elementsFromAuxiliary );
966 }
967
968 processRetrievedElements( aux, elementsFromAuxiliary );
969
970 elements.putAll( elementsFromAuxiliary );
971 }
972 }
973 }
974
975 return elements;
976 }
977
978
979
980
981
982
983
984
985 private void processRetrievedElements( AuxiliaryCache<K, V> aux, Map<K, ICacheElement<K, V>> elementsFromAuxiliary )
986 throws IOException
987 {
988 Iterator<ICacheElement<K, V>> elementFromAuxiliaryIterator = new HashMap<K, ICacheElement<K, V>>( elementsFromAuxiliary ).values().iterator();
989
990 while ( elementFromAuxiliaryIterator.hasNext() )
991 {
992 ICacheElement<K, V> element = elementFromAuxiliaryIterator.next();
993
994
995 if ( element != null )
996 {
997 if ( isExpired( element ) )
998 {
999 if ( log.isDebugEnabled() )
1000 {
1001 log.debug( cacheAttr.getCacheName() + " - Aux cache[" + aux.getCacheName() + "] hit, but element expired." );
1002 }
1003
1004
1005
1006
1007
1008 doExpires(element);
1009 elementsFromAuxiliary.remove( element.getKey() );
1010 }
1011 else
1012 {
1013 if ( log.isDebugEnabled() )
1014 {
1015 log.debug( cacheAttr.getCacheName() + " - Aux cache[" + aux.getCacheName() + "] hit" );
1016 }
1017
1018
1019 hitCountAux.incrementAndGet();
1020 copyAuxiliaryRetrievedItemToMemory( element );
1021 }
1022 }
1023 }
1024 }
1025
1026
1027
1028
1029
1030
1031
1032
1033 private void copyAuxiliaryRetrievedItemToMemory( ICacheElement<K, V> element )
1034 throws IOException
1035 {
1036 if ( memCache.getCacheAttributes().getMaxObjects() > 0 )
1037 {
1038 memCache.update( element );
1039 }
1040 else
1041 {
1042 if ( log.isDebugEnabled() )
1043 {
1044 log.debug( "Skipping memory update since no items are allowed in memory" );
1045 }
1046 }
1047 }
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057 private Set<K> pruneKeysFound( Set<K> keys, Map<K, ICacheElement<K, V>> foundElements )
1058 {
1059 Set<K> remainingKeys = new HashSet<K>( keys );
1060
1061 for (K key : foundElements.keySet())
1062 {
1063 remainingKeys.remove( key );
1064 }
1065
1066 return remainingKeys;
1067 }
1068
1069
1070
1071
1072
1073
1074 public Set<K> getKeySet()
1075 {
1076 return getKeySet(false);
1077 }
1078
1079
1080
1081
1082
1083
1084
1085
1086 public Set<K> getKeySet(boolean localOnly)
1087 {
1088 HashSet<K> allKeys = new HashSet<K>();
1089
1090 allKeys.addAll( memCache.getKeySet() );
1091 for ( AuxiliaryCache<K, V> aux : auxCaches )
1092 {
1093 if ( aux != null )
1094 {
1095 if(!localOnly || aux.getCacheType() == CacheType.DISK_CACHE)
1096 {
1097 try
1098 {
1099 allKeys.addAll( aux.getKeySet() );
1100 }
1101 catch ( IOException e )
1102 {
1103
1104 }
1105 }
1106 }
1107 }
1108 return allKeys;
1109 }
1110
1111
1112
1113
1114
1115
1116
1117
1118 @Override
1119 public boolean remove( K key )
1120 {
1121 return remove( key, false );
1122 }
1123
1124
1125
1126
1127
1128
1129
1130 public boolean localRemove( K key )
1131 {
1132 return remove( key, true );
1133 }
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152 protected boolean remove( K key, boolean localOnly )
1153 {
1154 removeCount.incrementAndGet();
1155
1156 boolean removed = false;
1157
1158 synchronized (this)
1159 {
1160 try
1161 {
1162 removed = memCache.remove( key );
1163 }
1164 catch ( IOException e )
1165 {
1166 log.error( e );
1167 }
1168
1169
1170 for ( ICache<K, V> aux : auxCaches )
1171 {
1172 if ( aux == null )
1173 {
1174 continue;
1175 }
1176
1177 CacheType cacheType = aux.getCacheType();
1178
1179
1180
1181 if ( localOnly && ( cacheType == CacheType.REMOTE_CACHE || cacheType == CacheType.LATERAL_CACHE ) )
1182 {
1183 continue;
1184 }
1185 try
1186 {
1187 if ( log.isDebugEnabled() )
1188 {
1189 log.debug( "Removing " + key + " from cacheType" + cacheType );
1190 }
1191
1192 boolean b = aux.remove( key );
1193
1194
1195 if ( !removed && cacheType != CacheType.REMOTE_CACHE )
1196 {
1197 removed = b;
1198 }
1199 }
1200 catch ( IOException ex )
1201 {
1202 log.error( "Failure removing from aux", ex );
1203 }
1204 }
1205 }
1206
1207 return removed;
1208 }
1209
1210
1211
1212
1213
1214
1215
1216 @Override
1217 public void removeAll()
1218 throws IOException
1219 {
1220 removeAll( false );
1221 }
1222
1223
1224
1225
1226
1227
1228 public void localRemoveAll()
1229 throws IOException
1230 {
1231 removeAll( true );
1232 }
1233
1234
1235
1236
1237
1238
1239
1240
1241 protected void removeAll( boolean localOnly )
1242 throws IOException
1243 {
1244 synchronized (this)
1245 {
1246 try
1247 {
1248 memCache.removeAll();
1249
1250 if ( log.isDebugEnabled() )
1251 {
1252 log.debug( "Removed All keys from the memory cache." );
1253 }
1254 }
1255 catch ( IOException ex )
1256 {
1257 log.error( "Trouble updating memory cache.", ex );
1258 }
1259
1260
1261 for ( ICache<K, V> aux : auxCaches )
1262 {
1263 if ( aux != null && ( aux.getCacheType() == CacheType.DISK_CACHE || !localOnly ) )
1264 {
1265 try
1266 {
1267 if ( log.isDebugEnabled() )
1268 {
1269 log.debug( "Removing All keys from cacheType" + aux.getCacheType() );
1270 }
1271
1272 aux.removeAll();
1273 }
1274 catch ( IOException ex )
1275 {
1276 log.error( "Failure removing all from aux", ex );
1277 }
1278 }
1279 }
1280 }
1281 }
1282
1283
1284
1285
1286 @Override
1287 public void dispose()
1288 {
1289 dispose( false );
1290 }
1291
1292
1293
1294
1295
1296
1297
1298
1299 public void dispose( boolean fromRemote )
1300 {
1301
1302 if ( alive.compareAndSet(true, false) == false )
1303 {
1304 return;
1305 }
1306
1307 if ( log.isInfoEnabled() )
1308 {
1309 log.info( "In DISPOSE, [" + this.cacheAttr.getCacheName() + "] fromRemote [" + fromRemote + "]" );
1310 }
1311
1312 synchronized (this)
1313 {
1314
1315
1316 if (cacheManager != null)
1317 {
1318 cacheManager.freeCache(getCacheName(), fromRemote);
1319 }
1320
1321
1322 if (future != null)
1323 {
1324 future.cancel(true);
1325 }
1326
1327
1328 if (elementEventQ != null)
1329 {
1330 elementEventQ.dispose();
1331 elementEventQ = null;
1332 }
1333
1334
1335
1336 for ( ICache<K, V> aux : auxCaches )
1337 {
1338 try
1339 {
1340
1341
1342
1343
1344 if ( aux == null || aux.getStatus() != CacheStatus.ALIVE
1345 || ( fromRemote && aux.getCacheType() == CacheType.REMOTE_CACHE ) )
1346 {
1347 if ( log.isInfoEnabled() )
1348 {
1349 log.info( "In DISPOSE, [" + this.cacheAttr.getCacheName() + "] SKIPPING auxiliary [" + aux.getCacheName() + "] fromRemote ["
1350 + fromRemote + "]" );
1351 }
1352 continue;
1353 }
1354
1355 if ( log.isInfoEnabled() )
1356 {
1357 log.info( "In DISPOSE, [" + this.cacheAttr.getCacheName() + "] auxiliary [" + aux.getCacheName() + "]" );
1358 }
1359
1360
1361
1362
1363
1364
1365
1366 if ( aux.getCacheType() == CacheType.DISK_CACHE )
1367 {
1368 int numToFree = memCache.getSize();
1369 memCache.freeElements( numToFree );
1370
1371 if ( log.isInfoEnabled() )
1372 {
1373 log.info( "In DISPOSE, [" + this.cacheAttr.getCacheName() + "] put " + numToFree + " into auxiliary " + aux.getCacheName() );
1374 }
1375 }
1376
1377
1378 aux.dispose();
1379 }
1380 catch ( IOException ex )
1381 {
1382 log.error( "Failure disposing of aux.", ex );
1383 }
1384 }
1385
1386 if ( log.isInfoEnabled() )
1387 {
1388 log.info( "In DISPOSE, [" + this.cacheAttr.getCacheName() + "] disposing of memory cache." );
1389 }
1390 try
1391 {
1392 memCache.dispose();
1393 }
1394 catch ( IOException ex )
1395 {
1396 log.error( "Failure disposing of memCache", ex );
1397 }
1398 }
1399 }
1400
1401
1402
1403
1404
1405
1406 public void save()
1407 {
1408 if ( alive.compareAndSet(true, false) == false )
1409 {
1410 return;
1411 }
1412
1413 synchronized ( this )
1414 {
1415 for ( ICache<K, V> aux : auxCaches )
1416 {
1417 try
1418 {
1419 if ( aux.getStatus() == CacheStatus.ALIVE )
1420 {
1421 for (K key : memCache.getKeySet())
1422 {
1423 ICacheElement<K, V> ce = memCache.get(key);
1424
1425 if (ce != null)
1426 {
1427 aux.update( ce );
1428 }
1429 }
1430 }
1431 }
1432 catch ( IOException ex )
1433 {
1434 log.error( "Failure saving aux caches.", ex );
1435 }
1436 }
1437 }
1438 if ( log.isDebugEnabled() )
1439 {
1440 log.debug( "Called save for [" + cacheAttr.getCacheName() + "]" );
1441 }
1442 }
1443
1444
1445
1446
1447
1448
1449
1450 @Override
1451 public int getSize()
1452 {
1453 return memCache.getSize();
1454 }
1455
1456
1457
1458
1459
1460
1461 @Override
1462 public CacheType getCacheType()
1463 {
1464 return CacheType.CACHE_HUB;
1465 }
1466
1467
1468
1469
1470
1471
1472 @Override
1473 public CacheStatus getStatus()
1474 {
1475 return alive.get() ? CacheStatus.ALIVE : CacheStatus.DISPOSED;
1476 }
1477
1478
1479
1480
1481
1482
1483 @Override
1484 public String getStats()
1485 {
1486 return getStatistics().toString();
1487 }
1488
1489
1490
1491
1492
1493
1494 public ICacheStats getStatistics()
1495 {
1496 ICacheStats stats = new CacheStats();
1497 stats.setRegionName( this.getCacheName() );
1498
1499
1500 ArrayList<IStatElement<?>> elems = new ArrayList<IStatElement<?>>();
1501
1502 elems.add(new StatElement<Integer>( "HitCountRam", Integer.valueOf(getHitCountRam()) ) );
1503 elems.add(new StatElement<Integer>( "HitCountAux", Integer.valueOf(getHitCountAux()) ) );
1504
1505 stats.setStatElements( elems );
1506
1507
1508 int total = auxCaches.length + 1;
1509 ArrayList<IStats> auxStats = new ArrayList<IStats>(total);
1510
1511 auxStats.add(getMemoryCache().getStatistics());
1512
1513 for ( AuxiliaryCache<K, V> aux : auxCaches )
1514 {
1515 auxStats.add(aux.getStatistics());
1516 }
1517
1518
1519 stats.setAuxiliaryCacheStats( auxStats );
1520
1521 return stats;
1522 }
1523
1524
1525
1526
1527
1528
1529 @Override
1530 public String getCacheName()
1531 {
1532 return cacheAttr.getCacheName();
1533 }
1534
1535
1536
1537
1538
1539
1540
1541 public IElementAttributes getElementAttributes()
1542 {
1543 if ( attr != null )
1544 {
1545 return attr.clone();
1546 }
1547 return null;
1548 }
1549
1550
1551
1552
1553
1554
1555 public void setElementAttributes( IElementAttributes attr )
1556 {
1557 this.attr = attr;
1558 }
1559
1560
1561
1562
1563
1564
1565 public ICompositeCacheAttributes getCacheAttributes()
1566 {
1567 return this.cacheAttr;
1568 }
1569
1570
1571
1572
1573
1574
1575 public void setCacheAttributes( ICompositeCacheAttributes cattr )
1576 {
1577 this.cacheAttr = cattr;
1578
1579 this.memCache.initialize( this );
1580 }
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590 public IElementAttributes getElementAttributes( K key )
1591 throws CacheException, IOException
1592 {
1593 ICacheElement<K, V> ce = get( key );
1594 if ( ce == null )
1595 {
1596 throw new ObjectNotFoundException( "key " + key + " is not found" );
1597 }
1598 return ce.getElementAttributes();
1599 }
1600
1601
1602
1603
1604
1605
1606
1607
1608 public boolean isExpired( ICacheElement<K, V> element)
1609 {
1610 return isExpired(element, System.currentTimeMillis(),
1611 ElementEventType.EXCEEDED_MAXLIFE_ONREQUEST,
1612 ElementEventType.EXCEEDED_IDLETIME_ONREQUEST );
1613 }
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625 public boolean isExpired(ICacheElement<K, V> element, long timestamp,
1626 ElementEventType eventMaxlife, ElementEventType eventIdle)
1627 {
1628 try
1629 {
1630 IElementAttributes attributes = element.getElementAttributes();
1631
1632 if ( !attributes.getIsEternal() )
1633 {
1634
1635
1636 long maxLifeSeconds = attributes.getMaxLife();
1637 long createTime = attributes.getCreateTime();
1638
1639 final long timeFactorForMilliseconds = attributes.getTimeFactorForMilliseconds();
1640
1641 if ( maxLifeSeconds != -1 && ( timestamp - createTime ) > ( maxLifeSeconds * timeFactorForMilliseconds) )
1642 {
1643 if ( log.isDebugEnabled() )
1644 {
1645 log.debug( "Exceeded maxLife: " + element.getKey() );
1646 }
1647
1648 handleElementEvent( element, eventMaxlife );
1649
1650 return true;
1651 }
1652 long idleTime = attributes.getIdleTime();
1653 long lastAccessTime = attributes.getLastAccessTime();
1654
1655
1656
1657
1658
1659
1660 if ( ( idleTime != -1 ) && ( timestamp - lastAccessTime ) > idleTime * timeFactorForMilliseconds )
1661 {
1662 if ( log.isDebugEnabled() )
1663 {
1664 log.debug( "Exceeded maxIdle: " + element.getKey() );
1665 }
1666
1667 handleElementEvent( element, eventIdle );
1668
1669 return true;
1670 }
1671 }
1672 }
1673 catch ( Exception e )
1674 {
1675 log.error( "Error determining expiration period, expiring", e );
1676
1677 return true;
1678 }
1679
1680 return false;
1681 }
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692 public void handleElementEvent( ICacheElement<K, V> element, ElementEventType eventType )
1693 {
1694 ArrayList<IElementEventHandler> eventHandlers = element.getElementAttributes().getElementEventHandlers();
1695 if ( eventHandlers != null )
1696 {
1697 if ( log.isDebugEnabled() )
1698 {
1699 log.debug( "Element Handlers are registered. Create event type " + eventType );
1700 }
1701 if ( elementEventQ == null )
1702 {
1703 log.warn("No element event queue available for cache " + getCacheName());
1704 return;
1705 }
1706 IElementEvent<ICacheElement<K, V>> event = new ElementEvent<ICacheElement<K, V>>( element, eventType );
1707 for (IElementEventHandler hand : eventHandlers)
1708 {
1709 try
1710 {
1711 elementEventQ.addElementEvent( hand, event );
1712 }
1713 catch ( IOException e )
1714 {
1715 log.error( "Trouble adding element event to queue", e );
1716 }
1717 }
1718 }
1719 }
1720
1721
1722
1723
1724
1725
1726
1727
1728 private void createMemoryCache( ICompositeCacheAttributes cattr )
1729 {
1730 if ( memCache == null )
1731 {
1732 try
1733 {
1734 Class<?> c = Class.forName( cattr.getMemoryCacheName() );
1735 @SuppressWarnings("unchecked")
1736 IMemoryCache<K, V> newInstance = (IMemoryCache<K, V>) c.newInstance();
1737 memCache = newInstance;
1738 memCache.initialize( this );
1739 }
1740 catch ( Exception e )
1741 {
1742 log.warn( "Failed to init mem cache, using: LRUMemoryCache", e );
1743
1744 this.memCache = new LRUMemoryCache<K, V>();
1745 this.memCache.initialize( this );
1746 }
1747 }
1748 else
1749 {
1750 log.warn( "Refusing to create memory cache -- already exists." );
1751 }
1752 }
1753
1754
1755
1756
1757
1758
1759 public IMemoryCache<K, V> getMemoryCache()
1760 {
1761 return memCache;
1762 }
1763
1764
1765
1766
1767
1768
1769 public int getHitCountRam()
1770 {
1771 return hitCountRam.get();
1772 }
1773
1774
1775
1776
1777
1778 public int getHitCountAux()
1779 {
1780 return hitCountAux.get();
1781 }
1782
1783
1784
1785
1786
1787 public int getMissCountNotFound()
1788 {
1789 return missCountNotFound.get();
1790 }
1791
1792
1793
1794
1795
1796 public int getMissCountExpired()
1797 {
1798 return missCountExpired.get();
1799 }
1800
1801
1802
1803
1804 public int getUpdateCount()
1805 {
1806 return updateCount.get();
1807 }
1808
1809
1810
1811
1812
1813
1814 @Override
1815 public void setKeyMatcher( IKeyMatcher<K> keyMatcher )
1816 {
1817 if ( keyMatcher != null )
1818 {
1819 this.keyMatcher = keyMatcher;
1820 }
1821 }
1822
1823
1824
1825
1826
1827
1828 public IKeyMatcher<K> getKeyMatcher()
1829 {
1830 return this.keyMatcher;
1831 }
1832
1833
1834
1835
1836
1837
1838 @Override
1839 public String toString()
1840 {
1841 return getStats();
1842 }
1843 }