This is an automated email from the ASF dual-hosted git repository. tv pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-jcs.git
commit 1ffc96bef955857bbdaa0e3d0413a5863c459d0f Author: Thomas Vandahl <[email protected]> AuthorDate: Wed Feb 11 16:23:09 2026 +0100 Use Java14 instanceof --- .../apache/commons/jcs4/admin/JCSAdminBean.java | 4 +- .../jcs4/auxiliary/disk/AbstractDiskCache.java | 4 +- .../jcs4/auxiliary/disk/PurgatoryElement.java | 7 ++- .../jcs4/auxiliary/disk/block/BlockDiskCache.java | 12 ++--- .../auxiliary/disk/indexed/IndexedDiskCache.java | 14 +++--- .../disk/indexed/IndexedDiskElementDescriptor.java | 3 +- .../lateral/socket/tcp/LateralTCPCache.java | 7 ++- .../lateral/socket/tcp/LateralTCPCacheFactory.java | 4 +- .../remote/AbstractRemoteAuxiliaryCache.java | 14 +++--- .../remote/AbstractRemoteCacheListener.java | 8 +-- .../commons/jcs4/auxiliary/remote/RemoteCache.java | 6 +-- .../jcs4/auxiliary/remote/RemoteLocation.java | 16 +++--- .../remote/http/client/RemoteHttpCache.java | 6 +-- .../apache/commons/jcs4/engine/CacheElement.java | 8 +-- .../jcs4/engine/CacheElementSerialized.java | 8 +-- .../commons/jcs4/engine/PooledCacheEventQueue.java | 23 ++++++++- .../jcs4/engine/ZombieCacheServiceNonLocal.java | 15 ++---- .../jcs4/engine/control/CompositeCache.java | 7 ++- .../engine/control/CompositeCacheConfigurator.java | 9 ++-- .../AbstractDoubleLinkedListMemoryCache.java | 3 +- .../jcs4/engine/memory/AbstractMemoryCache.java | 8 +-- .../apache/commons/jcs4/log/MessageFormatter.java | 8 +-- .../jcs4/utils/discovery/DiscoveredService.java | 13 ++--- .../jcs4/utils/discovery/UDPDiscoveryManager.java | 5 +- .../jcs4/utils/discovery/UDPDiscoveryReceiver.java | 5 +- .../serialization/SerializationConversionUtil.java | 4 +- .../commons/jcs4/utils/struct/AbstractLRUMap.java | 3 +- .../jcs4/auxiliary/disk/DiskTestObject.java | 46 +++++------------ .../indexed/AbstractIndexDiskCacheUnitTest.java | 57 ++++++++++++---------- .../auxiliary/disk/indexed/DiskTestObjectUtil.java | 47 ++++++++---------- .../disk/indexed/IndexDiskCacheSizeUnitTest.java | 9 ++-- .../IndexedDiskCacheOptimizationUnitTest.java | 25 +++++----- 32 files changed, 193 insertions(+), 215 deletions(-) diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/admin/JCSAdminBean.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/admin/JCSAdminBean.java index 6a7d222e..5562d53a 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/admin/JCSAdminBean.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/admin/JCSAdminBean.java @@ -259,9 +259,9 @@ public class JCSAdminBean implements JCSJMXBean continue; } - if (ice instanceof CacheElementSerialized) + if (ice instanceof CacheElementSerialized serialized) { - size += ((CacheElementSerialized<K, V>) ice).getSerializedValue().length; + size += serialized.getSerializedValue().length; } else { diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/AbstractDiskCache.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/AbstractDiskCache.java index 817ed82b..6b8c950a 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/AbstractDiskCache.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/AbstractDiskCache.java @@ -111,10 +111,8 @@ public abstract class AbstractDiskCache<K, V> { // If the element is a PurgatoryElement<K, V> we must check to see // if it is still spoolable, and remove it from purgatory. - if ( element instanceof PurgatoryElement ) + if ( element instanceof PurgatoryElement<K, V> pe) { - final PurgatoryElement<K, V> pe = (PurgatoryElement<K, V>) element; - synchronized ( pe.getCacheElement() ) { // TODO consider a timeout. diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/PurgatoryElement.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/PurgatoryElement.java index da4ce99f..8afa24db 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/PurgatoryElement.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/PurgatoryElement.java @@ -63,12 +63,11 @@ public class PurgatoryElement<K, V> { return true; } - if (!(obj instanceof PurgatoryElement)) + if (obj instanceof PurgatoryElement pe) { - return false; + return Objects.equals(getKey(), pe.getKey()); } - final PurgatoryElement<?,?> other = (PurgatoryElement<?,?>) obj; - return Objects.equals(getKey(), other.getKey()); + return false; } /** diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/block/BlockDiskCache.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/block/BlockDiskCache.java index 1d09e9c3..f4bcf6e5 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/block/BlockDiskCache.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/block/BlockDiskCache.java @@ -309,7 +309,7 @@ public class BlockDiskCache<K, V> // remove all keys of the same name group. final List<K> itemsToRemove = keyStore.keySet() .stream() - .filter(k -> k instanceof GroupAttrName && ((GroupAttrName<?>) k).groupId().equals(key)) + .filter(k -> k instanceof GroupAttrName gan && gan.groupId().equals(key)) .collect(Collectors.toList()); // remove matches. @@ -336,7 +336,7 @@ public class BlockDiskCache<K, V> // remove all keys of the same name hierarchy. final List<K> itemsToRemove = keyStore.keySet() .stream() - .filter(k -> k instanceof String && k.toString().startsWith(key)) + .filter(k -> k instanceof String s && s.startsWith(key)) .collect(Collectors.toList()); // remove matches. @@ -493,13 +493,13 @@ public class BlockDiskCache<K, V> try { - if (key instanceof String && key.toString().endsWith(NAME_COMPONENT_DELIMITER)) + if (key instanceof String s && s.endsWith(NAME_COMPONENT_DELIMITER)) { - removed = performPartialKeyRemoval((String) key); + removed = performPartialKeyRemoval(s); } - else if (key instanceof GroupAttrName && ((GroupAttrName<?>) key).attrName() == null) + else if (key instanceof GroupAttrName gan && gan.attrName() == null) { - removed = performGroupRemoval(((GroupAttrName<?>) key).groupId()); + removed = performGroupRemoval(gan.groupId()); } else { diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexedDiskCache.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexedDiskCache.java index af0f3bf3..4c3c0421 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexedDiskCache.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexedDiskCache.java @@ -1132,7 +1132,7 @@ public class IndexedDiskCache<K, V> extends AbstractDiskCache<K, V> // remove all keys of the same name hierarchy. for (final K k : keyHash.keySet()) { - if (k instanceof GroupAttrName && ((GroupAttrName<?>) k).groupId().equals(key)) + if (k instanceof GroupAttrName gan && gan.groupId().equals(key)) { itemsToRemove.add(k); } @@ -1166,11 +1166,11 @@ public class IndexedDiskCache<K, V> extends AbstractDiskCache<K, V> boolean removed = false; // remove all keys of the same name hierarchy. - final List<K> itemsToRemove = new LinkedList<>(); + final List<K> itemsToRemove = new ArrayList<>(); for (final K k : keyHash.keySet()) { - if (k instanceof String && k.toString().startsWith(key)) + if (k instanceof String s && s.startsWith(key)) { itemsToRemove.add(k); } @@ -1351,13 +1351,13 @@ public class IndexedDiskCache<K, V> extends AbstractDiskCache<K, V> { storageLock.writeLock().lock(); - if (key instanceof String && key.toString().endsWith(NAME_COMPONENT_DELIMITER)) + if (key instanceof String s && s.endsWith(NAME_COMPONENT_DELIMITER)) { - removed = performPartialKeyRemoval((String) key); + removed = performPartialKeyRemoval(s); } - else if (key instanceof GroupAttrName && ((GroupAttrName<?>) key).attrName() == null) + else if (key instanceof GroupAttrName gan && gan.attrName() == null) { - removed = performGroupRemoval(((GroupAttrName<?>) key).groupId()); + removed = performGroupRemoval(gan.groupId()); } else { diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexedDiskElementDescriptor.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexedDiskElementDescriptor.java index 8c95c111..34a5bcfc 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexedDiskElementDescriptor.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexedDiskElementDescriptor.java @@ -82,9 +82,8 @@ public class IndexedDiskElementDescriptor { return false; } - if (o instanceof IndexedDiskElementDescriptor) + if (o instanceof IndexedDiskElementDescriptor ided) { - final IndexedDiskElementDescriptor ided = (IndexedDiskElementDescriptor)o; return pos == ided.pos && len == ided.len; } diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/lateral/socket/tcp/LateralTCPCache.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/lateral/socket/tcp/LateralTCPCache.java index b30062aa..6ac44da0 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/lateral/socket/tcp/LateralTCPCache.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/lateral/socket/tcp/LateralTCPCache.java @@ -80,9 +80,8 @@ public class LateralTCPCache<K, V> */ public void fixCache( final ICacheServiceNonLocal<K, V> restoredLateral ) { - if ( this.lateralCacheService instanceof ZombieCacheServiceNonLocal ) + if ( this.lateralCacheService instanceof ZombieCacheServiceNonLocal<K, V> zombie) { - final ZombieCacheServiceNonLocal<K, V> zombie = (ZombieCacheServiceNonLocal<K, V>) this.lateralCacheService; this.lateralCacheService = restoredLateral; try { @@ -218,9 +217,9 @@ public class LateralTCPCache<K, V> monitor.notifyError(); // could stop the net search if it is built and try to reconnect? - if ( ex instanceof IOException ) + if (ex instanceof IOException ioe) { - throw (IOException) ex; + throw ioe; } throw new IOException( ex.getMessage() ); } diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/lateral/socket/tcp/LateralTCPCacheFactory.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/lateral/socket/tcp/LateralTCPCacheFactory.java index 3444baba..0ed8b891 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/lateral/socket/tcp/LateralTCPCacheFactory.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/lateral/socket/tcp/LateralTCPCacheFactory.java @@ -330,8 +330,8 @@ public class LateralTCPCacheFactory { final String key = lca.getTcpServer(); - return (ICacheServiceNonLocal<K, V>) csnlInstances.compute(key, (name, service) -> { - + return (ICacheServiceNonLocal<K, V>) csnlInstances.compute(key, (name, service) -> + { ICacheServiceNonLocal<?, ?> newService = service; // If service creation did not succeed last time, force retry diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/AbstractRemoteAuxiliaryCache.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/AbstractRemoteAuxiliaryCache.java index 4290ef33..e9e73e2d 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/AbstractRemoteAuxiliaryCache.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/AbstractRemoteAuxiliaryCache.java @@ -126,10 +126,9 @@ public abstract class AbstractRemoteAuxiliaryCache<K, V> final ICacheServiceNonLocal<K, V> remote = (ICacheServiceNonLocal<K, V>)restoredRemote; final ICacheServiceNonLocal<K, V> prevRemote = getRemoteCacheService(); - if ( prevRemote instanceof ZombieCacheServiceNonLocal ) + if ( prevRemote instanceof ZombieCacheServiceNonLocal<K, V> zombie) { - final ZombieCacheServiceNonLocal<K, V> zombie = (ZombieCacheServiceNonLocal<K, V>) prevRemote; - setRemoteCacheService( remote ); + setRemoteCacheService(remote); try { zombie.propagateEvents( remote ); @@ -423,9 +422,10 @@ public abstract class AbstractRemoteAuxiliaryCache<K, V> // Never try to deserialize if you are a cluster client. Cluster // clients are merely intra-remote cache communicators. Remote caches are assumed // to have no ability to deserialize the objects. - if (retVal instanceof ICacheElementSerialized && this.getRemoteCacheAttributes().getRemoteType() != RemoteType.CLUSTER) + if (retVal instanceof ICacheElementSerialized<K, V> serialized && + this.getRemoteCacheAttributes().getRemoteType() != RemoteType.CLUSTER) { - retVal = SerializationConversionUtil.getDeSerializedCacheElement( (ICacheElementSerialized<K, V>) retVal, + retVal = SerializationConversionUtil.getDeSerializedCacheElement(serialized, super.getElementSerializer() ); } } @@ -458,7 +458,7 @@ public abstract class AbstractRemoteAuxiliaryCache<K, V> for (final Map.Entry<K, ICacheElement<K, V>> entry : rawResults.entrySet()) { ICacheElement<K, V> unwrappedResult = null; - if ( entry.getValue() instanceof ICacheElementSerialized ) + if (entry.getValue() instanceof ICacheElementSerialized<K, V> serialized) { // Never try to deserialize if you are a cluster client. Cluster // clients are merely intra-remote cache communicators. Remote caches are assumed @@ -466,7 +466,7 @@ public abstract class AbstractRemoteAuxiliaryCache<K, V> if ( this.getRemoteCacheAttributes().getRemoteType() != RemoteType.CLUSTER ) { unwrappedResult = SerializationConversionUtil - .getDeSerializedCacheElement( (ICacheElementSerialized<K, V>) entry.getValue(), + .getDeSerializedCacheElement(serialized, super.getElementSerializer() ); } } diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/AbstractRemoteCacheListener.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/AbstractRemoteCacheListener.java index 0c21dc83..99d3dc8b 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/AbstractRemoteCacheListener.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/AbstractRemoteCacheListener.java @@ -169,22 +169,22 @@ public abstract class AbstractRemoteCacheListener<K, V> { if ( irca.getRemoveUponRemotePut() ) { - log.debug( "PUTTING ELEMENT FROM REMOTE, ( invalidating ) " ); + log.debug("PUTTING ELEMENT FROM REMOTE, (invalidating)"); handleRemove( cb.getCacheName(), cb.getKey() ); } else { - log.debug( "PUTTING ELEMENT FROM REMOTE, ( updating ) " ); + log.debug("PUTTING ELEMENT FROM REMOTE, (updating)"); log.debug( "cb = {0}", cb ); // Eventually the instance of will not be necessary. - if ( cb instanceof ICacheElementSerialized ) + if (cb instanceof ICacheElementSerialized<K, V> serialized) { log.debug( "Object needs to be deserialized." ); try { cb = SerializationConversionUtil.getDeSerializedCacheElement( - (ICacheElementSerialized<K, V>) cb, this.elementSerializer ); + serialized, this.elementSerializer ); log.debug( "Deserialized result = {0}", cb ); } catch ( final IOException e ) diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/RemoteCache.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/RemoteCache.java index 7a3f698d..344d9599 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/RemoteCache.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/RemoteCache.java @@ -150,7 +150,7 @@ public class RemoteCache<K, V> log.error( message, ex ); // we should not switch if the existing is a zombie. - if ( !( getRemoteCacheService() instanceof ZombieCacheServiceNonLocal ) ) + if (!(getRemoteCacheService() instanceof ZombieCacheServiceNonLocal)) { // TODO make configurable setRemoteCacheService( new ZombieCacheServiceNonLocal<>( getRemoteCacheAttributes().getZombieQueueMaxSize() ) ); @@ -170,9 +170,9 @@ public class RemoteCache<K, V> facade.failover( facade.getPrimaryServer() ); } - if ( ex instanceof IOException ) + if (ex instanceof IOException ioe) { - throw (IOException) ex; + throw ioe; } throw new IOException( ex ); } diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/RemoteLocation.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/RemoteLocation.java index 96b45264..6df2938d 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/RemoteLocation.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/RemoteLocation.java @@ -84,16 +84,16 @@ public final class RemoteLocation { return true; } - if (!(obj instanceof RemoteLocation)) + if (obj instanceof RemoteLocation l) { - return false; + if ( this.host == null ) + { + return l.host == null && port == l.port; + } + return host.equals( l.host ) && port == l.port; } - final RemoteLocation l = (RemoteLocation) obj; - if ( this.host == null ) - { - return l.host == null && port == l.port; - } - return host.equals( l.host ) && port == l.port; + + return false; } /** diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/http/client/RemoteHttpCache.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/http/client/RemoteHttpCache.java index 53bd3523..b0874be8 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/http/client/RemoteHttpCache.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/auxiliary/remote/http/client/RemoteHttpCache.java @@ -92,7 +92,7 @@ public class RemoteHttpCache<K, V> throws IOException { // we should not switch if the existing is a zombie. - if ( !( getRemoteCacheService() instanceof ZombieCacheServiceNonLocal ) ) + if ( !( getRemoteCacheService() instanceof ZombieCacheServiceNonLocal)) { final String message = "Disabling remote cache due to error: " + msg; logError( cacheName, "", message ); @@ -103,9 +103,9 @@ public class RemoteHttpCache<K, V> monitor.notifyError( this ); } - if ( ex instanceof IOException ) + if (ex instanceof IOException ioe) { - throw (IOException) ex; + throw ioe; } throw new IOException( ex.getMessage() ); } diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/CacheElement.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/CacheElement.java index 5b0be068..fdced4d5 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/CacheElement.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/CacheElement.java @@ -87,12 +87,12 @@ public class CacheElement<K, V> { return true; } - if (!(obj instanceof CacheElement)) + if (obj instanceof CacheElement ce) { - return false; + return Objects.equals(key, ce.key); } - final CacheElement<?,?> other = (CacheElement<?,?>) obj; - return Objects.equals(key, other.key); + + return false; } /** diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/CacheElementSerialized.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/CacheElementSerialized.java index 5a397345..fc7e4572 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/CacheElementSerialized.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/CacheElementSerialized.java @@ -75,12 +75,12 @@ public class CacheElementSerialized<K, V> { return true; } - if (!(obj instanceof CacheElementSerialized)) + if (obj instanceof CacheElementSerialized ces) { - return false; + return Objects.equals(getKey(), ces.getKey()); } - final CacheElementSerialized<?,?> other = (CacheElementSerialized<?,?>) obj; - return Objects.equals(getKey(), other.getKey()); + + return false; } /** diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/PooledCacheEventQueue.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/PooledCacheEventQueue.java index 4c0e3a3d..23e4297e 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/PooledCacheEventQueue.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/PooledCacheEventQueue.java @@ -1,5 +1,24 @@ package org.apache.commons.jcs4.engine; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; @@ -141,9 +160,9 @@ public class PooledCacheEventQueue<K, V> pool = createPool(threadPoolName); - if (pool instanceof ThreadPoolExecutor) + if (pool instanceof ThreadPoolExecutor tpe) { - queue = ((ThreadPoolExecutor) pool).getQueue(); + queue = tpe.getQueue(); } } diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/ZombieCacheServiceNonLocal.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/ZombieCacheServiceNonLocal.java index 7143c3c1..0fb5da07 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/ZombieCacheServiceNonLocal.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/ZombieCacheServiceNonLocal.java @@ -227,6 +227,7 @@ public class ZombieCacheServiceNonLocal<K, V> * @param service * @throws Exception */ + @SuppressWarnings("unchecked") // Type checked by instanceof public synchronized void propagateEvents( final ICacheServiceNonLocal<K, V> service ) throws Exception { @@ -240,21 +241,15 @@ public class ZombieCacheServiceNonLocal<K, V> // for each item, call the appropriate service method final ZombieEvent event = queue.poll(); - if ( event instanceof PutEvent ) + if (event instanceof PutEvent putEvent) { - @SuppressWarnings("unchecked") // Type checked by instanceof - final - PutEvent<K, V> putEvent = (PutEvent<K, V>) event; service.update( putEvent.element, event.requesterId ); } - else if ( event instanceof RemoveEvent ) + else if (event instanceof RemoveEvent removeEvent) { - @SuppressWarnings("unchecked") // Type checked by instanceof - final - RemoveEvent<K> removeEvent = (RemoveEvent<K>) event; - service.remove( event.cacheName, removeEvent.key, event.requesterId ); + service.remove( event.cacheName, (K) removeEvent.key, event.requesterId ); } - else if ( event instanceof RemoveAllEvent ) + else if (event instanceof RemoveAllEvent) { service.removeAll( event.cacheName, event.requesterId ); } diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/control/CompositeCache.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/control/CompositeCache.java index c4208971..b24c33b8 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/control/CompositeCache.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/control/CompositeCache.java @@ -1418,9 +1418,9 @@ public class CompositeCache<K, V> TimeUnit.SECONDS); } - if (memCache instanceof IRequireScheduler) + if (memCache instanceof IRequireScheduler irs) { - ((IRequireScheduler) memCache).setScheduledExecutorService(scheduledExecutor); + irs.setScheduledExecutorService(scheduledExecutor); } } @@ -1520,8 +1520,7 @@ public class CompositeCache<K, V> throws IOException { - if (cacheElement.getKey() instanceof String - && cacheElement.getKey().toString().endsWith(NAME_COMPONENT_DELIMITER)) + if (cacheElement.getKey() instanceof String s && s.endsWith(NAME_COMPONENT_DELIMITER)) { throw new IllegalArgumentException("key must not end with " + NAME_COMPONENT_DELIMITER + " for a put operation"); diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/control/CompositeCacheConfigurator.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/control/CompositeCacheConfigurator.java index ee31b3c3..284f4065 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/control/CompositeCacheConfigurator.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/control/CompositeCacheConfigurator.java @@ -150,9 +150,9 @@ public class CompositeCacheConfigurator auxFac.setName( auxName ); - if ( auxFac instanceof IRequireScheduler) + if (auxFac instanceof IRequireScheduler irs) { - ((IRequireScheduler)auxFac).setScheduledExecutorService(ccm.getScheduledExecutorService()); + irs.setScheduledExecutorService(ccm.getScheduledExecutorService()); } auxFac.initialize(); @@ -421,10 +421,9 @@ public class CompositeCacheConfigurator if ( auxCache != null ) { - if (auxCache instanceof IRequireScheduler) + if (auxCache instanceof IRequireScheduler irs) { - ((IRequireScheduler) auxCache).setScheduledExecutorService( - ccm.getScheduledExecutorService()); + irs.setScheduledExecutorService(ccm.getScheduledExecutorService()); } auxList.add( auxCache ); diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/memory/AbstractDoubleLinkedListMemoryCache.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/memory/AbstractDoubleLinkedListMemoryCache.java index 59ddb649..955aebf7 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/memory/AbstractDoubleLinkedListMemoryCache.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/memory/AbstractDoubleLinkedListMemoryCache.java @@ -412,9 +412,8 @@ public abstract class AbstractDoubleLinkedListMemoryCache<K, V> extends Abstract log.error("key class={0}", key.getClass()); log.error("key hashCode={0}", key.hashCode()); log.error("key toString={0}", key.toString()); - if (key instanceof GroupAttrName) + if (key instanceof GroupAttrName name) { - final GroupAttrName<?> name = (GroupAttrName<?>) key; log.error("GroupID hashCode={0}", name.groupId().hashCode()); log.error("GroupID.class={0}", name.groupId().getClass()); log.error("AttrName hashCode={0}", name.attrName().hashCode()); diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/memory/AbstractMemoryCache.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/memory/AbstractMemoryCache.java index 612344b9..66f2343c 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/memory/AbstractMemoryCache.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/engine/memory/AbstractMemoryCache.java @@ -356,11 +356,11 @@ public abstract class AbstractMemoryCache<K, V> boolean removed = false; // handle partial removal - if (key instanceof String && ((String) key).endsWith(ICache.NAME_COMPONENT_DELIMITER)) + if (key instanceof String s && s.endsWith(ICache.NAME_COMPONENT_DELIMITER)) { removed = removeByHierarchy(key); } - else if (key instanceof GroupAttrName && ((GroupAttrName<?>) key).attrName() == null) + else if (key instanceof GroupAttrName gan && gan.attrName() == null) { removed = removeByGroup(key); } @@ -419,7 +419,7 @@ public abstract class AbstractMemoryCache<K, V> return map.entrySet().removeIf(entry -> { final K k = entry.getKey(); - if (k instanceof GroupAttrName && ((GroupAttrName<?>) k).groupId().equals(groupId)) + if (k instanceof GroupAttrName gan && gan.groupId().equals(groupId)) { lock.lock(); try @@ -451,7 +451,7 @@ public abstract class AbstractMemoryCache<K, V> return map.entrySet().removeIf(entry -> { final K k = entry.getKey(); - if (k instanceof String && ((String) k).startsWith(keyString)) + if (k instanceof String s && s.startsWith(keyString)) { lock.lock(); try diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/log/MessageFormatter.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/log/MessageFormatter.java index 77bbf513..d1c58c58 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/log/MessageFormatter.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/log/MessageFormatter.java @@ -46,9 +46,9 @@ public class MessageFormatter this.messagePattern = messagePattern; this.parameters = parameters; final int length = parameters == null ? 0 : parameters.length; - if (length > 0 && parameters[length - 1] instanceof Throwable) + if (length > 0 && parameters[length - 1] instanceof Throwable t) { - this.throwable = (Throwable) parameters[length - 1]; + this.throwable = t; } } @@ -69,9 +69,9 @@ public class MessageFormatter .toArray(); final int length = parameters.length; - if (length > 0 && parameters[length - 1] instanceof Throwable) + if (length > 0 && parameters[length - 1] instanceof Throwable t) { - this.throwable = (Throwable) parameters[length - 1]; + this.throwable = t; } } diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/discovery/DiscoveredService.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/discovery/DiscoveredService.java index 9728edb8..52c10388 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/discovery/DiscoveredService.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/discovery/DiscoveredService.java @@ -84,16 +84,13 @@ public class DiscoveredService { return true; } - if (otherArg == null || !(otherArg instanceof DiscoveredService)) + if (otherArg instanceof DiscoveredService ds) { - return false; + return Objects.equals(serviceAddress, ds.serviceAddress) && + servicePort == ds.servicePort; } - final DiscoveredService other = (DiscoveredService) otherArg; - if (!Objects.equals(serviceAddress, other.serviceAddress)) - { - return false; - } - return servicePort == other.servicePort; + + return false; } /** diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/discovery/UDPDiscoveryManager.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/discovery/UDPDiscoveryManager.java index b6c44dc3..6f7295d4 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/discovery/UDPDiscoveryManager.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/discovery/UDPDiscoveryManager.java @@ -86,10 +86,9 @@ public class UDPDiscoveryManager cacheMgr.registerShutdownObserver( newService ); // inject scheduler - if ( cacheMgr instanceof IProvideScheduler) + if (cacheMgr instanceof IProvideScheduler ips) { - newService.setScheduledExecutorService(((IProvideScheduler)cacheMgr) - .getScheduledExecutorService()); + newService.setScheduledExecutorService(ips.getScheduledExecutorService()); } newService.startup(); diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/discovery/UDPDiscoveryReceiver.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/discovery/UDPDiscoveryReceiver.java index 7e69cfed..fdbe9069 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/discovery/UDPDiscoveryReceiver.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/discovery/UDPDiscoveryReceiver.java @@ -45,8 +45,8 @@ import org.apache.commons.jcs4.utils.discovery.UDPDiscoveryMessage.BroadcastType import org.apache.commons.jcs4.utils.net.HostNameUtil; import org.apache.commons.jcs4.utils.serialization.StandardSerializer; import org.apache.commons.jcs4.utils.threadpool.PoolConfiguration; -import org.apache.commons.jcs4.utils.threadpool.ThreadPoolManager; import org.apache.commons.jcs4.utils.threadpool.PoolConfiguration.WhenBlockedPolicy; +import org.apache.commons.jcs4.utils.threadpool.ThreadPoolManager; /** Receives UDP Discovery messages. */ public class UDPDiscoveryReceiver @@ -272,12 +272,11 @@ public class UDPDiscoveryReceiver byteBuffer.get(bytes); final Object obj = serializer.deSerialize(bytes, null); - if (obj instanceof UDPDiscoveryMessage) + if (obj instanceof UDPDiscoveryMessage msg) { // Ensure that the address we're supposed to send to is, indeed, the address // of the machine on the other end of this connection. This guards against // instances where we don't exactly get the right local host address - final UDPDiscoveryMessage msg = (UDPDiscoveryMessage) obj; msg.setHost(sourceAddress.getHostString()); log.debug( "Read object from address [{0}], object=[{1}]", diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/serialization/SerializationConversionUtil.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/serialization/SerializationConversionUtil.java index d6193849..c8f2944c 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/serialization/SerializationConversionUtil.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/serialization/SerializationConversionUtil.java @@ -99,9 +99,9 @@ public class SerializationConversionUtil byte[] serializedValue = null; // if it has already been serialized, don't do it again. - if ( element instanceof ICacheElementSerialized ) + if (element instanceof ICacheElementSerialized<K, V> serialized) { - serializedValue = ( (ICacheElementSerialized<K, V>) element ).getSerializedValue(); + serializedValue = serialized.getSerializedValue(); } else { diff --git a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/struct/AbstractLRUMap.java b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/struct/AbstractLRUMap.java index 8dcaca55..a76095ee 100644 --- a/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/struct/AbstractLRUMap.java +++ b/commons-jcs4-core/src/main/java/org/apache/commons/jcs4/utils/struct/AbstractLRUMap.java @@ -479,9 +479,8 @@ public abstract class AbstractLRUMap<K, V> log.error( "key class={0}", key.getClass() ); log.error( "key hashCode={0}", key.hashCode() ); log.error( "key toString={0}", key.toString() ); - if ( key instanceof GroupAttrName ) + if ( key instanceof GroupAttrName name) { - final GroupAttrName<?> name = (GroupAttrName<?>) key; log.error( "GroupID hashCode={0}", name.groupId().hashCode() ); log.error( "GroupID.class={0}", name.groupId().getClass() ); log.error( "AttrName hashCode={0}", name.attrName().hashCode() ); diff --git a/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/DiskTestObject.java b/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/DiskTestObject.java index b3b4df33..c2a4d95b 100644 --- a/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/DiskTestObject.java +++ b/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/DiskTestObject.java @@ -25,57 +25,35 @@ import java.util.Arrays; /** * Resembles a cached image. */ -public class DiskTestObject implements Serializable +public record DiskTestObject( + /** Key */ + Integer id, + + /** Value */ + byte[] imageBytes +) implements Serializable { /** Don't change */ private static final long serialVersionUID = 1L; - /** - * Key - */ - public Integer id; - - /** - * Byte size - */ - public byte[] imageBytes; - - /** - * @param id - * @param imageBytes - */ - public DiskTestObject(final Integer id, final byte[] imageBytes) - { - this.id = id; - this.imageBytes = imageBytes; - } - /** * @see Object#equals(Object other) */ @Override public boolean equals(final Object other) { - if (other instanceof DiskTestObject) + if (other instanceof DiskTestObject o) { - final DiskTestObject o = (DiskTestObject) other; - if (id != null) { + if (id != null) + { return id.equals(o.id) && Arrays.equals(imageBytes, o.imageBytes); } - if (id == null && o.id == null) { + if (id == null && o.id == null) + { return Arrays.equals(imageBytes, o.imageBytes); } } return false; } - /** - * @see Object#hashCode() - */ - @Override - public int hashCode() - { - return id.hashCode(); - } - } diff --git a/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/AbstractIndexDiskCacheUnitTest.java b/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/AbstractIndexDiskCacheUnitTest.java index eda9bbed..7e4848d6 100644 --- a/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/AbstractIndexDiskCacheUnitTest.java +++ b/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/AbstractIndexDiskCacheUnitTest.java @@ -131,10 +131,11 @@ public abstract class AbstractIndexDiskCacheUnitTest{ final int numberToInsert = 20; final int bytes = 24; - final ICacheElement<Integer, DiskTestObject>[] elements = DiskTestObjectUtil.createCacheElementsWithTestObjects(numberToInsert, - bytes, cattr.getCacheName()); + final List<ICacheElement<Integer, DiskTestObject>> elements = DiskTestObjectUtil + .createCacheElementsWithTestObjects(numberToInsert, bytes, cattr.getCacheName()); - for (final ICacheElement<Integer, DiskTestObject> element : elements) { + for (final ICacheElement<Integer, DiskTestObject> element : elements) + { disk.processUpdate(element); } @@ -143,10 +144,10 @@ public abstract class AbstractIndexDiskCacheUnitTest{ Thread.yield(); // remove half of those added - final int numberToRemove = elements.length / 2; - for (int i = 0; i < numberToRemove; i++) + final int numberToRemove = elements.size() / 2; + for (final ICacheElement<Integer, DiskTestObject> element : elements.subList(0, numberToRemove)) { - disk.processRemove(elements[i].getKey()); + disk.processRemove(element.getKey()); } final long expectedSize = DiskTestObjectUtil.totalSize(elements, numberToRemove); @@ -158,9 +159,9 @@ public abstract class AbstractIndexDiskCacheUnitTest{ // add half as many as we removed. These should all use spots in the recycle bin. final int numberToAdd = numberToRemove / 2; - for (int i = 0; i < numberToAdd; i++) + for (final ICacheElement<Integer, DiskTestObject> element : elements.subList(0, numberToAdd)) { - disk.processUpdate(elements[i]); + disk.processUpdate(element); } final long expectedSize2 = DiskTestObjectUtil.totalSize(elements, numberToAdd); @@ -245,10 +246,11 @@ public abstract class AbstractIndexDiskCacheUnitTest{ final int numberToInsert = 20; final int bytes = 24; - final ICacheElement<Integer, DiskTestObject>[] elements = DiskTestObjectUtil.createCacheElementsWithTestObjects(numberToInsert, - bytes, cattr.getCacheName()); + final List<ICacheElement<Integer, DiskTestObject>> elements = DiskTestObjectUtil + .createCacheElementsWithTestObjects(numberToInsert, bytes, cattr.getCacheName()); - for (final ICacheElement<Integer, DiskTestObject> element : elements) { + for (final ICacheElement<Integer, DiskTestObject> element : elements) + { disk.processUpdate(element); } @@ -505,7 +507,8 @@ public abstract class AbstractIndexDiskCacheUnitTest{ diskCache.update(new CacheElement<>(cacheName, i + ":key", cacheName + " data " + i)); } - final Map<String, ICacheElement<String, String>> matchingResults = diskCache.getMatching("1.8.+"); + final Map<String, ICacheElement<String, String>> matchingResults = + diskCache.getMatching("1.8.+"); // VERIFY assertEquals( 10, matchingResults.size(), "Wrong number returned" ); @@ -569,10 +572,11 @@ public abstract class AbstractIndexDiskCacheUnitTest{ final IndexedDiskCache<Integer, DiskTestObject> disk = new IndexedDiskCache<>(cattr); final int bytes = 1; - final ICacheElement<Integer, DiskTestObject>[] elements = DiskTestObjectUtil.createCacheElementsWithTestObjects(numberToInsert, - bytes, cattr.getCacheName()); + final List<ICacheElement<Integer, DiskTestObject>> elements = DiskTestObjectUtil + .createCacheElementsWithTestObjects(numberToInsert, bytes, cattr.getCacheName()); - for (final ICacheElement<Integer, DiskTestObject> element : elements) { + for (final ICacheElement<Integer, DiskTestObject> element : elements) + { disk.processUpdate(element); } @@ -581,10 +585,10 @@ public abstract class AbstractIndexDiskCacheUnitTest{ Thread.yield(); // remove half - final int numberToRemove = elements.length / 2; - for (int i = 0; i < numberToRemove; i++) + final int numberToRemove = elements.size() / 2; + for (final ICacheElement<Integer, DiskTestObject> element : elements.subList(0, numberToRemove)) { - disk.processRemove(elements[i].getKey()); + disk.processRemove(element.getKey()); } // verify that the recycle bin has the correct amount. @@ -615,11 +619,12 @@ public abstract class AbstractIndexDiskCacheUnitTest{ // we will reuse these final int bytes = 1; - final ICacheElement<Integer, DiskTestObject>[] elements = DiskTestObjectUtil.createCacheElementsWithTestObjects(numberToInsert, - bytes, cattr.getCacheName()); + final List<ICacheElement<Integer, DiskTestObject>> elements = DiskTestObjectUtil + .createCacheElementsWithTestObjects(numberToInsert, bytes, cattr.getCacheName()); // Add some to the disk - for (final ICacheElement<Integer, DiskTestObject> element : elements) { + for (final ICacheElement<Integer, DiskTestObject> element : elements) + { disk.processUpdate(element); } @@ -628,10 +633,10 @@ public abstract class AbstractIndexDiskCacheUnitTest{ Thread.yield(); // remove half of those added - final int numberToRemove = elements.length / 2; - for (int i = 0; i < numberToRemove; i++) + final int numberToRemove = elements.size() / 2; + for (final ICacheElement<Integer, DiskTestObject> element : elements.subList(0, numberToRemove)) { - disk.processRemove(elements[i].getKey()); + disk.processRemove(element.getKey()); } // verify that the recycle bin has the correct amount. @@ -639,9 +644,9 @@ public abstract class AbstractIndexDiskCacheUnitTest{ // add half as many as we removed. These should all use spots in the recycle bin. final int numberToAdd = numberToRemove / 2; - for (int i = 0; i < numberToAdd; i++) + for (final ICacheElement<Integer, DiskTestObject> element : elements.subList(0, numberToAdd)) { - disk.processUpdate(elements[i]); + disk.processUpdate(element); } // verify that we used the correct number of spots diff --git a/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/DiskTestObjectUtil.java b/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/DiskTestObjectUtil.java index 160e88f7..53cd238c 100644 --- a/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/DiskTestObjectUtil.java +++ b/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/DiskTestObjectUtil.java @@ -20,6 +20,8 @@ package org.apache.commons.jcs4.auxiliary.disk.indexed; */ import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import java.util.Random; import org.apache.commons.jcs4.auxiliary.disk.DiskTestObject; @@ -33,42 +35,37 @@ import org.apache.commons.jcs4.utils.serialization.StandardSerializer; public class DiskTestObjectUtil { /** - * Creates an array of ICacheElements with DiskTestObjects with payloads the byte size. + * Creates a list of ICacheElements with DiskTestObjects with payloads the byte size. * * @param numToCreate * @param bytes * @param cacheName - * @return ICacheElement[] + * @return List of ICacheElement */ - public static ICacheElement<Integer, DiskTestObject>[] createCacheElementsWithTestObjects( final int numToCreate, final int bytes, final String cacheName ) + public static List<ICacheElement<Integer, DiskTestObject>> createCacheElementsWithTestObjects(final int numToCreate, final int bytes, final String cacheName) { - @SuppressWarnings("unchecked") - final - ICacheElement<Integer, DiskTestObject>[] elements = new ICacheElement[numToCreate]; + final List<ICacheElement<Integer, DiskTestObject>> elements = new ArrayList<>(numToCreate); for ( int i = 0; i < numToCreate; i++ ) { // 24 KB final int size = bytes * 1024; - final DiskTestObject tile = new DiskTestObject( Integer.valueOf( i ), new byte[size]); + final DiskTestObject tile = new DiskTestObject(Integer.valueOf(i), new byte[size]); - final ICacheElement<Integer, DiskTestObject> element = new CacheElement<>( cacheName, tile.id, tile ); - elements[i] = element; + elements.add(new CacheElement<>(cacheName, tile.id(), tile)); } return elements; } /** - * Creates an array of ICacheElements with DiskTestObjects with payloads the byte size. + * Creates a list of ICacheElements with DiskTestObjects with payloads the byte size. * * @param numToCreate * @param cacheName - * @return ICacheElement[] + * @return List of ICacheElement */ - public static ICacheElement<Integer, DiskTestObject>[] createCacheElementsWithTestObjectsOfVariableSizes( final int numToCreate, final String cacheName ) + public static List<ICacheElement<Integer, DiskTestObject>> createCacheElementsWithTestObjectsOfVariableSizes(final int numToCreate, final String cacheName) { - @SuppressWarnings("unchecked") - final - ICacheElement<Integer, DiskTestObject>[] elements = new ICacheElement[numToCreate]; + final List<ICacheElement<Integer, DiskTestObject>> elements = new ArrayList<>(numToCreate); final Random random = new Random( 89 ); for ( int i = 0; i < numToCreate; i++ ) { @@ -77,8 +74,7 @@ public class DiskTestObjectUtil final int size = ( bytes + 4 ) * 1024; final DiskTestObject tile = new DiskTestObject( Integer.valueOf( i ), new byte[size]); - final ICacheElement<Integer, DiskTestObject> element = new CacheElement<>( cacheName, tile.id, tile ); - elements[i] = element; + elements.add(new CacheElement<>( cacheName, tile.id(), tile)); } return elements; } @@ -91,14 +87,14 @@ public class DiskTestObjectUtil * @return size * @throws IOException */ - public static long totalSize( final DiskTestObject[] testObjects, final int endPosition ) + public static long totalSize(final DiskTestObject[] testObjects, final int endPosition) throws IOException { final StandardSerializer serializer = new StandardSerializer(); long total = 0; - for ( int i = 0; i < endPosition; i++ ) + for (int i = 0; i < endPosition; i++) { - final int tileSize = serializer.serialize( testObjects[i] ).length + IndexedDisk.HEADER_SIZE_BYTES; + final int tileSize = serializer.serialize(testObjects[i]).length + IndexedDisk.HEADER_SIZE_BYTES; total += tileSize; } return total; @@ -112,10 +108,10 @@ public class DiskTestObjectUtil * @return size * @throws IOException */ - public static <K, V> long totalSize( final ICacheElement<K, V>[] elements, final int endPosition ) + public static <K, V> long totalSize(final List<ICacheElement<K, V>> elements, final int endPosition) throws IOException { - return totalSize( elements, 0, endPosition ); + return totalSize(elements, 0, endPosition); } /** @@ -127,17 +123,16 @@ public class DiskTestObjectUtil * @return size * @throws IOException */ - public static <K, V> long totalSize( final ICacheElement<K, V>[] elements, final int startPosition, final int endPosition ) + public static <K, V> long totalSize(final List<ICacheElement<K, V>> elements, final int startPosition, final int endPosition) throws IOException { final StandardSerializer serializer = new StandardSerializer(); long total = 0; - for ( int i = startPosition; i < endPosition; i++ ) + for (final ICacheElement<K, V> element : elements.subList(startPosition, endPosition)) { - final int tileSize = serializer.serialize( elements[i] ).length + IndexedDisk.HEADER_SIZE_BYTES; + final int tileSize = serializer.serialize(element).length + IndexedDisk.HEADER_SIZE_BYTES; total += tileSize; } return total; } - } diff --git a/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexDiskCacheSizeUnitTest.java b/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexDiskCacheSizeUnitTest.java index 4f98273c..0188f80b 100644 --- a/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexDiskCacheSizeUnitTest.java +++ b/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexDiskCacheSizeUnitTest.java @@ -48,21 +48,20 @@ public class IndexDiskCacheSizeUnitTest extends AbstractIndexDiskCacheUnitTest { final IndexedDiskCacheAttributes cattr = getCacheAttributes(); cattr.setCacheName( "testRemoveItems" ); - cattr.setOptimizeAtRemoveCount( 7 ); - cattr.setMaxKeySize( 8); // 1kb DiskTestObject takes 1420 bytes, so 5*1420 = 7100, so to keep 5 ojbects, we need max key size of 8 + cattr.setOptimizeAtRemoveCount(7); + // 1kb DiskTestObject takes 1420 bytes, so 5*1420 = 7100, so to keep 5 objects, we need max key size of 8 + cattr.setMaxKeySize(8); cattr.setMaxPurgatorySize( 0 ); cattr.setDiskPath( "target/test-sandbox/BreakIndexTest" ); final IndexedDiskCache<String, DiskTestObject> disk = new IndexedDiskCache<>( cattr ); final String[] test = { "a", "bb", "ccc", "dddd", "eeeee", "ffffff", "ggggggg", "hhhhhhhhh", "iiiiiiiiii" }; final String[] expect = { null, "bb", "ccc", null, null, "ffffff", null, "hhhhhhhhh", "iiiiiiiiii" }; - final DiskTestObject value = DiskTestObjectUtil.createCacheElementsWithTestObjects( 1, 1, cattr .getCacheName())[0].getVal(); - //System.out.println( "------------------------- testRecycleBin " ); + final DiskTestObject value = new DiskTestObject(Integer.valueOf(0), new byte[1024]); for ( int i = 0; i < 6; i++ ) { final ICacheElement<String, DiskTestObject> element = new CacheElement<>( "testRecycleBin", "key:" + test[i], value); - //System.out.println( "About to add key:" + test[i] + " i = " + i ); disk.processUpdate( element ); } diff --git a/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexedDiskCacheOptimizationUnitTest.java b/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexedDiskCacheOptimizationUnitTest.java index 009bcfe9..deaa8b19 100644 --- a/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexedDiskCacheOptimizationUnitTest.java +++ b/commons-jcs4-core/src/test/java/org/apache/commons/jcs4/auxiliary/disk/indexed/IndexedDiskCacheOptimizationUnitTest.java @@ -3,6 +3,8 @@ package org.apache.commons.jcs4.auxiliary.disk.indexed; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.List; + import org.apache.commons.jcs4.auxiliary.disk.DiskTestObject; import org.apache.commons.jcs4.engine.behavior.ICacheElement; import org.apache.commons.jcs4.utils.timing.SleepUtil; @@ -54,35 +56,34 @@ class IndexedDiskCacheOptimizationUnitTest disk.removeAll(); final int numberToInsert = removeCount * 3; - final ICacheElement<Integer, DiskTestObject>[] elements = DiskTestObjectUtil - .createCacheElementsWithTestObjectsOfVariableSizes( numberToInsert, cattr.getCacheName() ); + final List<ICacheElement<Integer, DiskTestObject>> elements = DiskTestObjectUtil + .createCacheElementsWithTestObjectsOfVariableSizes(numberToInsert, cattr.getCacheName()); - for (final ICacheElement<Integer, DiskTestObject> element : elements) { + for (final ICacheElement<Integer, DiskTestObject> element : elements) + { disk.processUpdate( element ); } - Thread.sleep( 1000 ); + Thread.sleep(1000); final long sizeBeforeRemove = disk.getDataFileSize(); - // System.out.println( "file sizeBeforeRemove " + sizeBeforeRemove ); - // System.out.println( "totalSize inserted " + DiskTestObjectUtil.totalSize( elements, numberToInsert ) ); // DO WORK - for ( int i = 0; i < removeCount; i++ ) + for (int i = 0; i < removeCount; i++) { - disk.processRemove( Integer.valueOf( i ) ); + disk.processRemove(Integer.valueOf(i)); } - SleepUtil.sleepAtLeast( 1000 ); + SleepUtil.sleepAtLeast(1000); disk.optimizeFile(); // VERIFY final long sizeAfterRemove = disk.getDataFileSize(); - final long expectedSizeAfterRemove = DiskTestObjectUtil.totalSize( elements, removeCount, elements.length ); + final long expectedSizeAfterRemove = DiskTestObjectUtil.totalSize(elements, removeCount, elements.size() ); // test is prone to failure for timing reasons. - if ( expectedSizeAfterRemove != sizeAfterRemove ) + if (expectedSizeAfterRemove != sizeAfterRemove) { - SleepUtil.sleepAtLeast( 2000 ); + SleepUtil.sleepAtLeast(2000); } assertTrue( sizeAfterRemove < sizeBeforeRemove, "The post optimization size should be smaller."
