/
CacheMgt.java
792 lines (695 loc) · 20.9 KB
/
CacheMgt.java
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import org.adempiere.ad.dao.cache.CacheInvalidateMultiRequest;
import org.adempiere.ad.dao.cache.CacheInvalidateRequest;
import org.adempiere.ad.trx.api.ITrx;
import org.adempiere.ad.trx.api.ITrxListenerManager.TrxEventTiming;
import org.adempiere.ad.trx.api.ITrxManager;
import org.adempiere.ad.trx.api.OnTrxMissingPolicy;
import org.adempiere.util.Check;
import org.adempiere.util.Services;
import org.adempiere.util.WeakList;
import org.adempiere.util.jmx.JMXRegistry;
import org.adempiere.util.jmx.JMXRegistry.OnJMXAlreadyExistsPolicy;
import org.slf4j.Logger;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import de.metas.logging.LogManager;
import lombok.NonNull;
import lombok.Value;
/**
* Adempiere Cache Management
*
* @author Jorg Janke
* @version $Id: CacheMgt.java,v 1.2 2006/07/30 00:54:35 jjanke Exp $
*/
public final class CacheMgt
{
/**
* Get Cache Management
*
* @return Cache Manager
*/
public static final CacheMgt get()
{
return s_cache;
} // get
/** Singleton */
private static final CacheMgt s_cache = new CacheMgt();
public static final String JMX_BASE_NAME = "org.adempiere.cache";
/**
* Private Constructor
*/
private CacheMgt()
{
super();
JMXRegistry.get().registerJMX(new JMXCacheMgt(), OnJMXAlreadyExistsPolicy.Replace);
}
public static final int RECORD_ID_ALL = -1;
/** List of Instances */
private final WeakList<CacheInterface> cacheInstances = new WeakList<>();
private final ReentrantLock cacheInstancesLock = cacheInstances.getReentrantLock();
private CopyOnWriteArrayList<ICacheResetListener> globalCacheResetListeners = new CopyOnWriteArrayList<>();
/**
* List of Table Names.
*
* i.e. map of TableName to "how many cache instances do we have for that table name"
*/
private final Map<String, AtomicInteger> tableNames = new HashMap<>();
/* package */ static final transient Logger log = LogManager.getLogger(CacheMgt.class);
private final AtomicBoolean cacheResetRunning = new AtomicBoolean();
private final AtomicLong lastCacheReset = new AtomicLong();
/**
* Enable caches for the given table to be invalidated by remote events. Example: if a user somewhere else opens/closes a period, we can allow the system to invalidate the local cache to avoid it
* becoming stale.
*
* @param tableName
*/
public final void enableRemoteCacheInvalidationForTableName(final String tableName)
{
CacheInvalidationRemoteHandler.instance.enableForTableName(tableName);
}
/**************************************************************************
* Register Cache Instance
*
* @param instance Cache
* @return true if added
*/
public boolean register(final CacheInterface instance)
{
final Boolean registerWeak = null; // auto
return register(instance, registerWeak);
}
private boolean register(final CacheInterface instance, final Boolean registerWeak)
{
if (instance == null)
{
return false;
}
//
// Extract cache instance's tableName (if any)
final String tableName = getTableNameOrNull(instance);
//
// Determine if we shall register the cache instance weakly or not.
final boolean registerWeakEffective;
if (tableName != null)
{
registerWeakEffective = registerWeak == null ? true : registerWeak;
}
else
{
// NOTE: if the cache is not providing an TableName, we register them with a hard-reference because probably is a cache listener
registerWeakEffective = registerWeak == null ? false : registerWeak;
}
cacheInstancesLock.lock();
try
{
if (tableName != null)
{
//
// Increment tableName counter
tableNames
.computeIfAbsent(tableName, k -> new AtomicInteger(0))
.incrementAndGet();
}
return cacheInstances.add(instance, registerWeakEffective);
}
finally
{
cacheInstancesLock.unlock();
}
} // register
/**
* Un-Register Cache Instance
*
* @param instance Cache
* @return true if removed
*/
public boolean unregister(final CacheInterface instance)
{
if (instance == null)
{
return false;
}
final String tableName = getTableNameOrNull(instance);
cacheInstancesLock.lock();
try
{
int countRemoved = 0;
// Could be included multiple times
final int size = cacheInstances.size();
for (int i = size - 1; i >= 0; i--)
{
final CacheInterface stored = cacheInstances.get(i);
if (instance.equals(stored))
{
cacheInstances.remove(i);
countRemoved++;
}
}
//
// Remove it from tableNames
if (tableName != null)
{
final AtomicInteger count = tableNames.remove(tableName);
if (count == null)
{
// let it removed
}
else
{
final int countNew = count.get() - countRemoved;
if (countNew > 0)
{
count.set(countNew);
tableNames.put(tableName, count);
}
}
}
final boolean found = countRemoved > 0;
return found;
}
finally
{
cacheInstancesLock.unlock();
}
} // unregister
/**
* Extracts the TableName from given cache instance.
*
* @param instance
* @return table name or <code>null</code> if table name could not be extracted
*/
private static final String getTableNameOrNull(final CacheInterface instance)
{
if (instance instanceof ITableAwareCacheInterface)
{
final ITableAwareCacheInterface recordsCache = (ITableAwareCacheInterface)instance;
// Try cache TableName
final String tableName = recordsCache.getTableName();
if (tableName != null && !tableName.isEmpty())
{
return tableName;
}
// Try cache Name
final String cacheName = recordsCache.getName();
if (cacheName != null && !cacheName.isEmpty())
{
return cacheName;
}
// Fallback: return null because there is no table, no cache name
return null;
}
// Fallback for any other cache interfaces: return null because TableName is not available
return null;
}
public Set<String> getTableNames()
{
return ImmutableSet.copyOf(tableNames.keySet());
}
public Set<String> getTableNamesToBroadcast()
{
return CacheInvalidationRemoteHandler.instance.getTableNamesToBroadcast();
}
/** @return last time cache reset timestamp */
public long getLastCacheReset()
{
return lastCacheReset.get();
}
/**
* Invalidate ALL cached entries of all registered {@link CacheInterface}s.
*
* @return how many cache entries were invalidated
*/
public int reset()
{
// Do nothing if already running (i.e. avoid recursion)
if (cacheResetRunning.getAndSet(true))
{
return 0;
}
cacheInstancesLock.lock();
int counter = 0;
int total = 0;
try
{
for (final CacheInterface cacheInstance : cacheInstances)
{
if (cacheInstance != null && cacheInstance.size() > 0)
{
total += resetNoFail(cacheInstance);
counter++;
}
}
fireGlobalCacheResetListeners(CacheInvalidateMultiRequest.all());
lastCacheReset.incrementAndGet();
}
finally
{
cacheInstancesLock.unlock();
cacheResetRunning.set(false);
}
log.info("Reset all: {} cache instances invalidated ({} cached items invalidated)", counter, total);
return total;
}
private void fireGlobalCacheResetListeners(final CacheInvalidateMultiRequest multiRequest)
{
for (ICacheResetListener globalCacheResetListener : globalCacheResetListeners)
{
try
{
globalCacheResetListener.reset(multiRequest);
}
catch (final Exception ex)
{
log.warn("Failed reseting {}. Ignored.", globalCacheResetListener, ex);
}
}
}
/**
* Invalidate all cached entries for given TableName.
*
* @param tableName table name
* @return how many cache entries were invalidated
*/
public int reset(final String tableName)
{
final CacheInvalidateMultiRequest request = CacheInvalidateMultiRequest.fromTableNameAndRecordId(tableName, RECORD_ID_ALL);
return reset(request, ResetMode.LOCAL_AND_BROADCAST);
} // reset
/**
* Invalidate all cached entries for given TableName.
*
* The event won't be broadcasted.
*
* @param tableName table name
* @return how many cache entries were invalidated
*/
public int resetLocal(final String tableName)
{
final CacheInvalidateMultiRequest request = CacheInvalidateMultiRequest.fromTableNameAndRecordId(tableName, RECORD_ID_ALL);
return reset(request, ResetMode.LOCAL);
} // reset
/**
* Invalidate all cached entries for given TableName/Record_ID.
*
* @param tableName table name
* @param recordId record if applicable or {@link #RECORD_ID_ALL} for all
* @return how many cache entries were invalidated
*/
public int reset(final String tableName, final int recordId)
{
final CacheInvalidateMultiRequest request = CacheInvalidateMultiRequest.fromTableNameAndRecordId(tableName, recordId);
return reset(request, ResetMode.LOCAL_AND_BROADCAST);
}
public int reset(final CacheInvalidateRequest request)
{
return reset(CacheInvalidateMultiRequest.of(request), ResetMode.LOCAL_AND_BROADCAST);
}
/**
* Reset cache for TableName/Record_ID when given transaction is committed.
*
* If no transaction was given or given transaction was not found, the cache is reset right away.
*
* @param trxName
* @param tableName
* @param recordId
*/
public void resetLocalNowAndBroadcastOnTrxCommit(final String trxName, final CacheInvalidateRequest request)
{
final ITrxManager trxManager = Services.get(ITrxManager.class);
final ITrx trx = trxManager.get(trxName, OnTrxMissingPolicy.ReturnTrxNone);
if (trxManager.isNull(trx))
{
reset(request);
return;
}
else
{
reset(CacheInvalidateMultiRequest.of(request), ResetMode.LOCAL);
RecordsToResetOnTrxCommitCollector.getCreate(trx).addRecord(request, ResetMode.JUST_BROADCAST);
}
}
static enum ResetMode
{
LOCAL, LOCAL_AND_BROADCAST, JUST_BROADCAST;
public boolean isResetLocal()
{
return this == LOCAL || this == LOCAL_AND_BROADCAST;
}
public boolean isBroadcast()
{
return this == LOCAL_AND_BROADCAST || this == JUST_BROADCAST;
}
}
/**
* Invalidate all cached entries for given TableName/Record_ID.
*
* @param tableName
* @param recordId
* @param broadcast true if we shall also broadcast this remotely.
* @return how many cache entries were invalidated (estimated!)
*/
final int reset(@NonNull final CacheInvalidateMultiRequest multiRequest, @NonNull final ResetMode mode)
{
final int resetCount;
if (mode.isResetLocal())
{
resetCount = resetCacheInstances(multiRequest);
//
fireGlobalCacheResetListeners(multiRequest);
}
else
{
resetCount = 0;
}
//
// Broadcast cache invalidation.
// We do this, even if we don't have any cache interface registered locally, because there might be remotely.
if (mode.isBroadcast())
{
CacheInvalidationRemoteHandler.instance.postEvent(multiRequest);
}
return resetCount;
} // reset
private final int resetCacheInstances(final CacheInvalidateMultiRequest multiRequest)
{
if (multiRequest.isResetAll())
{
return reset();
}
cacheInstancesLock.lock();
try
{
int total = 0;
for (final CacheInvalidateRequest request : multiRequest.getRequests())
{
final int totalPerRequest = resetCacheInterfacesNoLock(request);
total += totalPerRequest;
}
return total;
}
finally
{
cacheInstancesLock.unlock();
}
}
private int resetCacheInterfacesNoLock(final CacheInvalidateRequest request)
{
final String tableName = request.getTableNameEffective();
final int recordId = request.getRecordIdEffective();
// optimization: skip if there is no cache interface registered for request's tableName
if (!tableNames.containsKey(tableName))
{
return 0;
}
int total = 0;
int counter = 0;
//
// Invalidate local caches if we have at least one cache interface about our table
for (final CacheInterface cacheInstance : cacheInstances)
{
if (cacheInstance == null)
{
// nothing to reset
}
else if (cacheInstance instanceof CCache)
{
// NOTE: CCache requires all reset events, even if they were not it's table.
// inside checks if table matches OR if it's cache name starts with given table name.
// A total fucked up, not performant.
// FIXME at least we shall use ConcurrentSkipListMap and prepare the steps to switch to some well known cache frameworks.
final ITableAwareCacheInterface recordsCache = (ITableAwareCacheInterface)cacheInstance;
final int itemsRemoved = recordsCache.resetForRecordId(tableName, recordId);
if (itemsRemoved > 0)
{
log.debug("Rest cache instance for {}/{}: {}", tableName, recordId, cacheInstance);
total += itemsRemoved;
counter++;
}
}
else if (cacheInstance instanceof ITableAwareCacheInterface)
{
if (tableName.equals(((ITableAwareCacheInterface)cacheInstance).getTableName()))
{
final ITableAwareCacheInterface recordsCache = (ITableAwareCacheInterface)cacheInstance;
final int itemsRemoved = recordsCache.resetForRecordId(tableName, recordId);
if (itemsRemoved > 0)
{
log.debug("Rest cache instance for {}/{}: {}", tableName, recordId, cacheInstance);
total += itemsRemoved;
counter++;
}
}
}
else
{
// NOTE: for other cache implementations we shall skip reseting by tableName/key because they don't support it.
// e.g. de.metas.adempiere.report.jasper.client.JRClient.cacheListener, org.adempiere.ad.dao.cache.impl.ModelCacheService.ModelCacheService()
log.debug("Unknown cache instance to reset: {}", cacheInstance);
}
}
log.debug("Reset {}: {} cache interfaces affected ({} records invalidated)", tableName, counter, total);
return total;
}
/**
* Total Cached Elements
*
* @return count
*/
public int getElementCount()
{
int total = 0;
cacheInstancesLock.lock();
try
{
for (final CacheInterface cacheInstance : cacheInstances)
{
if (cacheInstance == null)
{
// do nothing
}
else
{
total += cacheInstance.size();
}
}
}
finally
{
cacheInstancesLock.unlock();
}
return total;
} // getElementCount
/**
* String Representation
*
* @return info
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder("CacheMgt[");
sb.append("Instances=")
.append(cacheInstances.size())
.append("]");
return sb.toString();
} // toString
/**
* Extended String Representation
*
* @return info
*/
public String toStringX()
{
StringBuilder sb = new StringBuilder("CacheMgt[");
sb.append("Instances=")
.append(cacheInstances.size())
.append(", Elements=").append(getElementCount())
.append("]");
return sb.toString();
} // toString
/**
* Reset cache and clear ALL registered {@link CacheInterface}s.
*/
public void clear()
{
cacheInstancesLock.lock();
try
{
reset();
// Make sure all cache instances are reset
for (final CacheInterface cacheInstance : cacheInstances)
{
if (cacheInstance == null)
{
continue;
}
resetNoFail(cacheInstance);
}
cacheInstances.clear();
tableNames.clear();
}
finally
{
cacheInstancesLock.unlock();
}
}
private int resetNoFail(final CacheInterface cacheInstance)
{
try
{
return cacheInstance.reset();
}
catch (Exception e)
{
// log but don't fail
log.warn("Error while reseting {}. Ignored.", cacheInstance, e);
return 0;
}
}
/**
* Adds an listener which will be fired when the cache for given table is about to be reset.
*
* @param tableName
* @param cacheResetListener
*/
public void addCacheResetListener(@NonNull final String tableName, @NonNull final ICacheResetListener cacheResetListener)
{
final Boolean registerWeak = Boolean.FALSE;
register(CacheResetListener2CacheInterface.of(tableName, cacheResetListener), registerWeak);
}
public void addCacheResetListener(@NonNull final ICacheResetListener cacheResetListener)
{
globalCacheResetListeners.addIfAbsent(cacheResetListener);
}
@Value
private static final class CacheResetListener2CacheInterface implements ITableAwareCacheInterface
{
public static final CacheResetListener2CacheInterface of(@NonNull final String tableName, @NonNull final ICacheResetListener listener)
{
return new CacheResetListener2CacheInterface(tableName, listener);
}
private final String tableName;
private final ICacheResetListener listener;
private CacheResetListener2CacheInterface(@NonNull final String tableName, @NonNull final ICacheResetListener listener)
{
Check.assumeNotEmpty(tableName, "tableName not empty");
this.tableName = tableName;
this.listener = listener;
}
@Override
public int size()
{
return 1;
}
@Override
public String getName()
{
return tableName;
}
@Override
public String getTableName()
{
return tableName;
}
@Override
public int reset()
{
return listener.reset(CacheInvalidateMultiRequest.allRecordsForTable(tableName));
}
@Override
public int resetForRecordId(final String tableName, final int recordId)
{
return listener.reset(CacheInvalidateMultiRequest.fromTableNameAndRecordId(tableName, recordId));
}
}
/** Collects records that needs to be removed from cache when a given transaction is committed */
private static final class RecordsToResetOnTrxCommitCollector
{
/** Gets/creates the records collector which needs to be reset when transaction is committed */
public static final RecordsToResetOnTrxCommitCollector getCreate(final ITrx trx)
{
return trx.getProperty(TRX_PROPERTY, () -> {
final RecordsToResetOnTrxCommitCollector collector = new RecordsToResetOnTrxCommitCollector();
// Listens {@link ITrx}'s after-commit and fires enqueued cache invalidation requests
trx.getTrxListenerManager()
.newEventListener().timing(TrxEventTiming.AFTER_COMMIT)
.handlingMethod(innerTrx -> {
final RecordsToResetOnTrxCommitCollector innerCollector = innerTrx.getProperty(TRX_PROPERTY);
if (innerCollector == null)
{
return;
}
innerCollector.sendRequestsAndClear();
})
.register();
return collector;
});
}
private static final String TRX_PROPERTY = RecordsToResetOnTrxCommitCollector.class.getName();
private final Map<CacheInvalidateRequest, ResetMode> request2resetMode = Maps.newConcurrentMap();
/** Enqueues a record */
public final void addRecord(@NonNull final CacheInvalidateRequest request, @NonNull ResetMode resetMode)
{
request2resetMode.put(request, resetMode);
log.debug("Scheduled cache invalidation on transaction commit: {} ({})", request, resetMode);
}
/** Reset the cache for all enqueued records */
private void sendRequestsAndClear()
{
if (request2resetMode.isEmpty())
{
return;
}
final CacheMgt cacheMgt = CacheMgt.get();
final ImmutableList.Builder<CacheInvalidateRequest> resetLocalRequestsBuilder = ImmutableList.builder();
final ImmutableList.Builder<CacheInvalidateRequest> broadcastRequestsBuilder = ImmutableList.builder();
request2resetMode.forEach((request, resetMode) -> {
if (resetMode.isResetLocal())
{
resetLocalRequestsBuilder.add(request);
}
if (resetMode.isBroadcast())
{
broadcastRequestsBuilder.add(request);
}
});
final ImmutableList<CacheInvalidateRequest> resetLocalRequests = resetLocalRequestsBuilder.build();
if (!resetLocalRequests.isEmpty())
{
cacheMgt.reset(CacheInvalidateMultiRequest.of(resetLocalRequests), ResetMode.LOCAL);
}
final ImmutableList<CacheInvalidateRequest> broadcastRequests = broadcastRequestsBuilder.build();
if (!broadcastRequests.isEmpty())
{
cacheMgt.reset(CacheInvalidateMultiRequest.of(broadcastRequests), ResetMode.JUST_BROADCAST);
}
request2resetMode.clear();
}
}
}