auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static String resolvePath(String path, String relativeTo) { if (new File(path).isAbsolute()) { return path; } else if (relativeTo != null) { return new File(new File(relativeTo), path).getAbsolutePath(); } else { return path; } START } END This can be reduced to ```java if (!new File(path).isAbsolute() && relativeTo != null) { return new File(new File(relativeTo), path).getAbsolutePath(); } return path; ```

Target:
public static String resolvePath(String path, String relativeTo) { if (path == null) { return null; } else if (new File(path).isAbsolute()) { return path; } else if (relativeTo != null) { return new File(new File(relativeTo), path).getAbsolutePath(); } else { return path; } }
Source:
public ConfigurationBuilder getDefaultConfigurationBuilder() { START return globalConfigurationBuilder.defaultCacheName().map(namedConfigurationBuilders::get).orElse(null); END } Technically this is another lambda and out of scope of this PR imo.

Target:
public ConfigurationBuilder getDefaultConfigurationBuilder() { if (globalConfigurationBuilder.defaultCacheName().isPresent()) { return namedConfigurationBuilders.get(globalConfigurationBuilder.defaultCacheName().get()); } else { return null; } }
Source:
public CompletionStage<Void> setAvailabilityMode(AvailabilityMode availabilityMode) { if (availabilityMode != this.availabilityMode) { START if (notifier.hasListener(PartitionStatusChanged.class)) { END return notifier.notifyPartitionStatusChanged(availabilityMode, true) .thenCompose(ignore -> { updateAvailabilityMode(availabilityMode); return notifier.notifyPartitionStatusChanged(availabilityMode, false); }); } else { return updateAvailabilityMode(availabilityMode); } } else { return CompletableFutures.completedNull(); } } This isn't really that performance-sensitive

Target:
public CompletionStage<Void> setAvailabilityMode(AvailabilityMode availabilityMode) { if (availabilityMode != this.availabilityMode) { return notifier.notifyPartitionStatusChanged(availabilityMode, true) .thenCompose(ignore -> { updateAvailabilityMode(availabilityMode); return notifier.notifyPartitionStatusChanged(availabilityMode, false); }); } else { return CompletableFutures.completedNull(); } }
Source:
public static void unregisterMBean(ObjectName objectName, MBeanServer mBeanServer) throws Exception { START if (objectName != null && mBeanServer.isRegistered(objectName)) { END SecurityActions.unregisterMBean(objectName, mBeanServer); log.tracef("Unregistered %s", objectName); } } IMO the caller should do this check, in fact most callers already do.

Target:
public static void unregisterMBean(ObjectName objectName, MBeanServer mBeanServer) throws Exception { if (mBeanServer.isRegistered(objectName)) { SecurityActions.unregisterMBean(objectName, mBeanServer); log.tracef("Unregistered %s", objectName); } }
Source:
public int getStatus() { START return response.getStatus().code(); END } `response.status().code()`

Target:
public int getStatus() { return response.status().code(); }
Source:
private String getParameterValue(RestRequest restRequest, String name) { List<String> values = restRequest.parameters().get(name); if (values == null) return null; START return values.iterator().next(); END } return `values == null ? null : values.iterator().next();`

Target:
private String getParameterValue(RestRequest restRequest, String name) { List<String> values = restRequest.parameters().get(name); return values == null ? null : values.iterator().next(); }
Source:
START public Class<? extends AtomicKeySetImpl> getJavaClass() { END return AtomicKeySetImpl.class; } getJavaClass() should declare the exact class. no need for wildcards. not just here, everywhere.

Target:
public Class<AtomicKeySetImpl> getJavaClass() { return AtomicKeySetImpl.class; }
Source:
public void setServers(Collection<SocketAddress> servers) { this.servers = servers.toArray(new SocketAddress[servers.size()]); // keep the old index if possible so that we don't produce more requests for the first server if (index >= this.servers.length) { START index = ThreadLocalRandom.current().nextInt(this.servers.length); END } if (trace) { log.tracef("New server list is: " + Arrays.toString(this.servers)); } } Shouldn't `index` be initialized to MAX_INT in order to trigger this on 1st call ?

Target:
public void setServers(Collection<SocketAddress> servers) { this.servers = servers.toArray(new SocketAddress[servers.size()]); // Always start with a random server after a topology update index = ThreadLocalRandom.current().nextInt(this.servers.length); if (trace) { log.tracef("New server list is: " + Arrays.toString(this.servers)); } }
Source:
public AssertsNearCache<K, V> expectNearPreemptiveRemove(K key, AssertsNearCache<K, V>... affected) { START if (nearCacheMode.invalidated()) { END // Preemptive remove MockRemoveEvent preemptiveRemove = pollEvent(events); assertEquals(key, preemptiveRemove.key); } expectNoNearEvents(); return this; } Don't have eager near cache anymore...

Target:
public AssertsNearCache<K, V> expectNearPreemptiveRemove(K key, AssertsNearCache<K, V>... affected) { // Preemptive remove MockRemoveEvent preemptiveRemove = pollEvent(events); assertEquals(key, preemptiveRemove.key); expectNoNearEvents(); return this; }
Source:
public boolean isObjectStorage() { START boolean storageHinted = status == NO_ERROR_STATUS_OBJ_STORAGE END || status == SUCCESS_WITH_PREVIOUS_OBJ_STORAGE || status == NOT_EXECUTED_WITH_PREVIOUS_OBJ_STORAGE; boolean objectMediaType = keyMediaType != null && keyMediaType.match(MediaType.APPLICATION_OBJECT); return storageHinted || objectMediaType; } I'm not sure I like these checks staying here. They should be moved to Codec28 so that these checks are only done if using HR protocol 2.8 (or whichever is the last HR protocol version that sent them). If you leave them here, you're going to carry checking even with protocol 2.9 which is wasteful since the server does not send them.

Target:
public boolean isObjectStorage() { return keyMediaType != null && keyMediaType.match(MediaType.APPLICATION_OBJECT); }
Source:
public void afterClass() { START embeddedCacheManager.stop(); END remoteCacheManager.stop(); hotrodServer.stop(); } Why change the order? You normally stop in opposite order to creation. So, if you create embedded cache manager first and then the server, you normally stop server first, then the cache manager.

Target:
public void afterClass() { remoteCacheManager.stop(); hotrodServer.stop(); embeddedCacheManager.stop(); }
Source:
private static void assertXaException(ExceptionRunnable runnable, int errorCode) { try { runnable.run(); fail(); } catch (Exception e) { Exceptions.assertException(XAException.class, e); //noinspection ConstantConditions START assertEquals(errorCode, ((XAException) e).errorCode); END } } `assertException` doesn't really help here, I'd rather do something like this: private static void assertXaException(ExceptionRunnable runnable, int errorCode) throws Exception { try { runnable.run(); fail(); } catch (XAException e) { assertEquals(errorCode, e.errorCode); } } I'd also move the helper methods after the tests.

Target:
private static void assertXaException(ExceptionRunnable runnable, int errorCode) throws Exception { try { runnable.run(); fail(); } catch (XAException e) { assertEquals(errorCode, e.errorCode); } }
Source:
public Builder<?> read(NearCacheConfiguration template) { mode = template.mode(); maxEntries = template.maxEntries(); Pattern pattern = template.cacheNamePattern(); START cacheNamePattern = pattern; END return this; } Can be just `cacheNamePattern = template.cacheNamePattern();`

Target:
public Builder<?> read(NearCacheConfiguration template) { mode = template.mode(); maxEntries = template.maxEntries(); cacheNamePattern = template.cacheNamePattern(); return this; }
Source:
public IndependentClustersMergeTest() { this.numMembersInCluster = 2; this.mergePolicy = (preferredEntry, otherEntries) -> { START CacheEntry entry = preferredEntry != null ? preferredEntry : (CacheEntry) otherEntries.get(0); END entry.setValue(MERGE_RESULT); return entry; }; } Unnecessary cast. Could also avoid the unchecked warning by declaring `entry` and `mergePolicy` with generic parameters `<String, String>`.

Target:
public IndependentClustersMergeTest() { this.numMembersInCluster = 2; this.mergePolicy = (preferredEntry, otherEntries) -> { CacheEntry<String, String> entry = preferredEntry != null ? preferredEntry : otherEntries.get(0); entry.setValue(MERGE_RESULT); return entry; }; }
Source:
public static SmallIntSet of(int i1) { START SmallIntSet set = new SmallIntSet(1); END set.set(i1); return set; } Maybe `i1 + 1`? Same in the other `of(...)` methods, the constructor parameter is the end of the range.

Target:
public static SmallIntSet of(int i1) { SmallIntSet set = new SmallIntSet(); set.set(i1); return set; }
Source:
private static void closeIterator(Iterator<?> iter) { START if (iter != null && iter instanceof CloseableIterator) { END ((CloseableIterator) iter).close(); } } unnecessary null check

Target:
private static void closeIterator(Iterator<?> iter) { if (iter instanceof CloseableIterator) { ((CloseableIterator) iter).close(); } }
Source:
private int getSegment(Object key) { if (cacheMode.needsStateTransfer()) { return keyPartitioner.getSegment(key); } // LOCAL and INVAL don't require segments, so just use 0 START return 0; END } Maybe we should change `KeyPartitionerFactory` to return a `k -> 0` partitioner in local and invalidation caches instead

Target:
private int getSegment(Object key) { return keyPartitioner.getSegment(key); }
Source:
public V get(Object key) { assertKeyNotNull(key); START checkCanRun(cache, componentRegistry); END InternalCacheEntry<K, V> ice = getDataContainer().get(key); if (ice != null) { return ice.getValue(); } return null; } `componentRegistry` can be removed (`cache.getName()`)

Target:
public V get(Object key) { assertKeyNotNull(key); checkCanRun(cache, cache.getName()); InternalCacheEntry<K, V> ice = getDataContainer().get(key); if (ice != null) { return ice.getValue(); } return null; }
Source:
protected void writeCommandParameters(ObjectOutput output, ReplicableCommand command) throws IOException { command.writeTo(output); if (command instanceof TopologyAffectedCommand) { output.writeInt(((TopologyAffectedCommand) command).getTopologyId()); } if (command instanceof SegmentSpecificCommand) { START UnsignedNumeric.writeUnsignedInt(output, ((SegmentSpecificCommand) command).getSegment()); END } } -1, IMO the commands should write/read the segment themselves

Target:
protected void writeCommandParameters(ObjectOutput output, ReplicableCommand command) throws IOException { command.writeTo(output); if (command instanceof TopologyAffectedCommand) { output.writeInt(((TopologyAffectedCommand) command).getTopologyId()); } }
Source:
public ConfigurationBuilder() { this.classLoader = new WeakReference<>(Thread.currentThread().getContextClassLoader()); this.connectionPool = new ConnectionPoolConfigurationBuilder(this); this.asyncExecutorFactory = new ExecutorFactoryConfigurationBuilder(this); this.security = new SecurityConfigurationBuilder(this); this.nearCache = new NearCacheConfigurationBuilder(this); START transaction = new TransactionConfigurationBuilder(this); END } for symmetry either qualify the field with this. or remove the others :smile:

Target:
public ConfigurationBuilder() { this.classLoader = new WeakReference<>(Thread.currentThread().getContextClassLoader()); this.connectionPool = new ConnectionPoolConfigurationBuilder(this); this.asyncExecutorFactory = new ExecutorFactoryConfigurationBuilder(this); this.security = new SecurityConfigurationBuilder(this); this.nearCache = new NearCacheConfigurationBuilder(this); this.transaction = new TransactionConfigurationBuilder(this); }
Source:
START public void stop() { END if (trace) { log.tracef("Stopping LocalTopologyManager on %s", transport.getAddress()); } running = false; for (LocalCacheStatus cache : runningCaches.values()) { cache.getTopologyUpdatesExecutor().shutdownNow(); } withinThreadExecutor.shutdown(); persistentUUIDManager.removePersistentAddressMapping(persistentUUID); } We should really have proper dependency graphs to avoid these "conjured" numbers

Target:
public void stop() { if (trace) { log.tracef("Stopping LocalTopologyManager on %s", transport.getAddress()); } running = false; for (LocalCacheStatus cache : runningCaches.values()) { cache.getTopologyUpdatesExecutor().shutdownNow(); } withinThreadExecutor.shutdown(); }
Source:
void sendCommand(Address target, ReplicableCommand command, long requestId, DeliverOrder deliverOrder, boolean rsvp, boolean noRelay, boolean checkView) { Message message = new Message(toJGroupsAddress(target)); marshallRequest(message, command, requestId); setMessageFlags(message, deliverOrder, rsvp, noRelay); START if (checkView && !clusterView.contains(target)) END return; send(message); } Maybe this should be the first thing in the method?

Target:
void sendCommand(Address target, ReplicableCommand command, long requestId, DeliverOrder deliverOrder, boolean rsvp, boolean noRelay, boolean checkView) { if (checkView && !clusterView.contains(target)) return; Message message = new Message(toJGroupsAddress(target)); marshallRequest(message, command, requestId); setMessageFlags(message, deliverOrder, rsvp, noRelay); send(message); }
Source:
public void startConflictResolution(ConsistentHash conflictCH, List<Address> mergeMembers) { topology = new CacheTopology(topology.getTopologyId() + 1, topology.getRebalanceId() + 1, START conflictCH, conflictCH, conflictCH, END CacheTopology.Phase.CONFLICT_RESOLUTION, mergeMembers, persistentUUIDs(mergeMembers)); } Ok, so removing only the union CH doesn't work, but now that I got you to use the conflict CH for reading, how about we only set the `currentCH` and change `CacheTopology` to use it for everything during `CONFLICT_RESOLUTION`?

Target:
public void startConflictResolution(ConsistentHash conflictCH, List<Address> mergeMembers) { topology = new CacheTopology(topology.getTopologyId() + 1, topology.getRebalanceId() + 1, conflictCH, null, CacheTopology.Phase.CONFLICT_RESOLUTION, mergeMembers, persistentUUIDs(mergeMembers)); }
Source:
synchronized void completeRequest() { List<Map<Address, CacheEntry<K, V>>> retVal = keyReplicaMap.entrySet().stream() .map(Map.Entry::getValue) START .collect(Collectors.toList()); END clear(); future.complete(Collections.unmodifiableList(retVal)); } Could we get away with returning `keyReplicaMap.values()` here?

Target:
synchronized void completeRequest() { List<Map<Address, CacheEntry<K, V>>> retVal = new ArrayList<>(keyReplicaMap.values()); clear(); future.complete(Collections.unmodifiableList(retVal)); }
Source:
public CacheImpl(String name) { this.name = name; START this.contextBuilder = this::getInvocationContextWithImplicitTransaction; END this.pferContextBuilder = this::putForExternalReadContext; } I would prefer to initialize these inline in field declaration rather than constructor... If I am not nitpicking too much...

Target:
public CacheImpl(String name) { this.name = name; }
Source:
public void onUpdate(CounterEvent event) { try { queue.put(event); START log.tracef("[%s] add event %s", name, event); END } catch (InterruptedException e) { log.errorf(e, "[%s] interrupted while adding event %s", name, event); } } isTraceEnabled is not necessary here ?

Target:
public void onUpdate(CounterEvent event) { try { queue.put(event); if (trace) { log.tracef("[%s] add event %s", name, event); } } catch (InterruptedException e) { log.errorf(e, "[%s] interrupted while adding event %s", name, event); } }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DataConversion that = (DataConversion) o; return Objects.equals(encoder, that.encoder) && Objects.equals(wrapper, that.wrapper) && Objects.equals(transcoder, that.transcoder) && START isKey == that.isKey; END } Putting ```isKey == that.isKey``` first will make the comparison fail faster :)

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DataConversion that = (DataConversion) o; return isKey == that.isKey && Objects.equals(encoder, that.encoder) && Objects.equals(wrapper, that.wrapper) && Objects.equals(transcoder, that.transcoder); }
Source:
public boolean isReadable(int size) { START return buffer.isReadable(); // see readableBytes(); END } should this be `buffer.isReadable(size)` ?

Target:
public boolean isReadable(int size) { return buffer.isReadable(size); // see readableBytes(); }
Source:
public Integer getNumberOfLocalConnections() { START return Integer.valueOf(acceptedChannels.size()); END } Unnecessary boxing?

Target:
public Integer getNumberOfLocalConnections() { return acceptedChannels.size(); }
Source:
START public SslConfiguration(boolean enabled, boolean requireClientAuth, Map<String, SslEngineConfiguration> sniDomainsConfiguration) { END this.enabled = enabled; this.requireClientAuth = requireClientAuth; this.sniDomainsConfiguration = sniDomainsConfiguration; } At the minute your code utilises `SslConfigurationBuilder(null)` in the `SinglePortRouterBuilder` and `new SslConfiguration(..)` is never called outside of the builder. So this is a bit different to your description unless I am missing something. Do you intend to use the `SslConfiguration` constructor later?

Target:
SslConfiguration(boolean enabled, boolean requireClientAuth, Map<String, SslEngineConfiguration> sniDomainsConfiguration) { this.enabled = enabled; this.requireClientAuth = requireClientAuth; this.sniDomainsConfiguration = sniDomainsConfiguration; }
Source:
static Configuration getCacheConfiguration(final AdvancedCache<?, ?> cache) { GetCacheConfigurationAction action = new GetCacheConfigurationAction(cache); START return doPrivileged(action); END } ```doPrivileged(cache::getCacheConfiguration)``` ?

Target:
static Configuration getCacheConfiguration(final AdvancedCache<?, ?> cache) { return doPrivileged(cache::getCacheConfiguration); }
Source:
void progress(String message, String color) { if (useColor) { progress(color + message + RESET); } else START progress(message); END } Not using curly on the ```else``` branch? :)

Target:
void progress(String message, String color) { if (useColor) { progress(color + message + RESET); } else { progress(message); } }
Source:
public CacheQuery<E> sort(Sort sort) { START this.sort = sort; END this.queryDefinition.setSort(sort); return super.sort(sort); } Is the ```sort``` field used at all? I see it being set but don't see it used anywhere.

Target:
public CacheQuery<E> sort(Sort sort) { this.queryDefinition.setSort(sort); return super.sort(sort); }
Source:
public ClusteredQueryCommandWorker getCommand(Cache<?, ?> cache, QueryDefinition queryDefinition, UUID lazyQueryId, int docIndex) { START ClusteredQueryCommandWorker command = null; END command = getNewInstance(); command.init(cache, queryDefinition, lazyQueryId, docIndex); return command; } Declaration and initialization of ```command``` can be done in same line.

Target:
public ClusteredQueryCommandWorker getCommand(Cache<?, ?> cache, QueryDefinition queryDefinition, UUID lazyQueryId, int docIndex) { ClusteredQueryCommandWorker command = getNewInstance(); command.init(cache, queryDefinition, lazyQueryId, docIndex); return command; }
Source:
public void inject(GlobalConfiguration globalConfiguration, EmbeddedCacheManager cacheManager) { START this.globalConfiguration = globalConfiguration; END this.cacheManager = cacheManager; this.localConfigurationManager = globalConfiguration.globalState().localConfigurationManager(); } don't you want to create a factory for it? so it can be injected :)

Target:
public void inject(GlobalConfiguration globalConfiguration, EmbeddedCacheManager cacheManager) { this.cacheManager = cacheManager; this.localConfigurationManager = globalConfiguration.globalState().localConfigurationManager(); }
Source:
public static MergePolicy fromConfiguration(EntryMergePolicy policy) { if (policy == null) return NONE; for (MergePolicy mp : MergePolicy.values()) START if (mp.impl != null && Objects.equals(mp.impl.getClass(), policy.getClass())) END return mp; return CUSTOM; } If the enum implemented `EntryMergePolicy` directly, you could find the configured one with `mp == policy`.

Target:
public static MergePolicy fromConfiguration(EntryMergePolicy policy) { if (policy == null) return NONE; for (MergePolicy mp : MergePolicy.values()) if (mp == policy) return mp; return CUSTOM; }
Source:
private boolean resolveConflictsOnMerge(Configuration config, CacheMode cacheMode) { if (config == null || cacheMode.isScattered() || cacheMode.isInvalidation()) return false; ClusteringConfiguration cc = config.clustering(); START return cc.partitionHandling().resolveConflictsOnMerge() && cc.hash().numOwners() > 1; END } These checks would work better in `PartitionHandlingConfigurationBuilder.validate()`, logging warnings if the merge policy is ignored. Although I'm not sure the `numOwners > 1` check is really needed...

Target:
private boolean resolveConflictsOnMerge(Configuration config, CacheMode cacheMode) { if (config == null || cacheMode.isScattered() || cacheMode.isInvalidation()) return false; return config.clustering().partitionHandling().resolveConflictsOnMerge(); }
Source:
protected Object[] parameterValues() { START String partitions = String.format("{%s, %s}", Arrays.toString(p0.getNodes()), Arrays.toString(p1.getNodes())); END return concat(super.parameterValues(), partitions); } Interpreting something like `DenyReadWriteRemoveAllTest[[0, 1, 2], [3]] failed` in the test results seems kind of tough, I'd like to give each partition scenarios a name instead. TBH I only started thinking about this when I saw the some `factory()` implementations and I realized I had no idea how `new int[]{0,1,2}, new int[]{3}` changes the test compared to `new int[]{0,1}, new int[]{2}`.

Target:
protected Object[] parameterValues() { return concat(super.parameterValues(), description); }
Source:
public boolean resolveConflictsOnMerge() { EntryMergePolicy policy = mergePolicy(); START return (policy instanceof MergePolicy && policy != MergePolicy.NONE) || policy != null; END } I'm afraid this is equivalent to `policy != null`, it doesn't return `false` if `policy == NONE`. I suggest `if (policy == NONE) return false; else return policy != null`.

Target:
public boolean resolveConflictsOnMerge() { EntryMergePolicy policy = mergePolicy(); if (policy == MergePolicy.NONE) return false; return policy != null; }
Source:
void stop() { if (trace) log.tracef("Stop called on ReplicaSpliterator. Current segment %s", nextSegment); START if (isConflictResolutionInProgress()) END segmentRequestFuture.cancel(true); } I think `stop()` could be called before any `tryAdvance()`, so I'd replace the condition with a `null` check on `segmentRequestFuture`.

Target:
void stop() { if (trace) log.tracef("Stop called on ReplicaSpliterator. Current segment %s", nextSegment); if (segmentRequestFuture != null) segmentRequestFuture.cancel(true); }
Source:
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { ackTarget = (Address) input.readObject(); if (ackTarget != null) { id = input.readLong(); } topologyId = input.readInt(); keys = MarshallUtil.unmarshallCollection(input, ArrayList::new); START if (keys == null) { END segments = MarshallUtil.unmarshallIntCollection(input, SmallIntSet::new); } } your luck is that the keys are never `null` otherwise you wouldn't be able to read the command.

Target:
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { ackTarget = (Address) input.readObject(); if (ackTarget != null) { id = input.readLong(); } topologyId = input.readInt(); keys = MarshallUtil.unmarshallCollection(input, ArrayList::new); }
Source:
protected CompletableFuture<?> completeSingleWriteOnPrimaryOriginator(DataWriteCommand command, Address backup, CompletableFuture<?> rpcFuture) { CompletableFuture<?> revokeFuture = revokeBiasSync(command.getKey(), backup, command.getTopologyId()); START return revokeFuture == null ? rpcFuture : CompletableFuture.allOf(rpcFuture, revokeFuture); END } `revokeFuture` is never `null`

Target:
protected CompletableFuture<?> completeSingleWriteOnPrimaryOriginator(DataWriteCommand command, Address backup, CompletableFuture<?> rpcFuture) { CompletableFuture<?> revokeFuture = revokeBiasSync(command.getKey(), backup, command.getTopologyId()); return CompletableFuture.allOf(rpcFuture, revokeFuture); }
Source:
private static PathElement counterElement(ModelNode operation) START throws OperationFailedException { END final PathAddress address = pathAddress(operation.require(OP_ADDR)); final PathElement counterElement = address.getElement(address.size() - 1); return counterElement; } `OperationFailedException` never thrown and it can be removed

Target:
private static PathElement counterElement(ModelNode operation) { final PathAddress address = pathAddress(operation.require(OP_ADDR)); final PathElement counterElement = address.getElement(address.size() - 1); return counterElement; }
Source:
public void stop(StopContext context) { // remove and destroy the counter instance EmbeddedCacheManager container = this.dependencies.getCacheContainer(); CounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager(container); START counterManager.remove(counterConfigurationName); END } this is the cause of the persistent problem. you are deleting the counter from the persistent storage!

Target:
public void stop(StopContext context) { // intentionally empty as we don't do anything on service stop }
Source:
public BoundedOffHeapDataContainer(int desiredSize, long maxSize, EvictionType type) { super(desiredSize); this.maxSize = maxSize; if (type == EvictionType.COUNT) { sizeCalculator = i -> 1; } else { // Use size of entry plus 16 for our LRU pointers START sizeCalculator = i -> offHeapEntryFactory.getSize(i) + OffHeapLruNode.getSize(); END } this.lruLock = new ReentrantLock(); firstAddress = 0; } Doesn't `offHeapEntryFactory.getSize()` include the size of the LRU pointers?

Target:
public BoundedOffHeapDataContainer(int desiredSize, long maxSize, EvictionType type) { super(desiredSize); this.maxSize = maxSize; if (type == EvictionType.COUNT) { sizeCalculator = i -> 1; } else { // Use size of entry plus 16 for our LRU pointers sizeCalculator = i -> offHeapEntryFactory.getSize(i); } this.lruLock = new ReentrantLock(); firstAddress = 0; }
Source:
public void removeCache(CacheEntryRemovedEvent<ScopedState, CacheState> event) { String cacheName = event.getKey().getName(); START gcm.log.debugf("Remove cache %s", cacheName); END gcm.localRemoveCache(cacheName); } Do we want a message for create as well?

Target:
public void removeCache(CacheEntryRemovedEvent<ScopedState, CacheState> event) { String cacheName = event.getKey().getName(); gcm.localRemoveCache(cacheName); }
Source:
public void removeCache(String cacheName) { authzHelper.checkPermission(AuthorizationPermission.ADMIN); START if (cacheManagerAdmin != null) END cacheManagerAdmin.removeCache(cacheName); else { RemoveCacheCommand.removeCache(this, cacheName); } } I don't think the `cacheManagerAdmin` can be `null`

Target:
public void removeCache(String cacheName) { cacheManagerAdmin.removeCache(cacheName); }
Source:
protected void entryReplaced(long newAddress, long oldAddress) { long oldSize = sizeCalculator.applyAsLong(oldAddress); long newSize = sizeCalculator.applyAsLong(newAddress); lruLock.lock(); try { if (trace) { START log.tracef("Replacing LRU node: OldValue: 0x%016x NewValue: 0x%016x", oldAddress, END newAddress); } removeNode(oldAddress); addEntryAddressToEnd(newAddress); currentSize += newSize; currentSize -= oldSize; // Must only remove entry while holding lru lock now super.entryReplaced(newAddress, oldAddress); } finally { lruLock.unlock(); } } `removeNode` and `addEntryAddressToEnd` both log, so maybe we can remove this log ,essage.

Target:
protected void entryReplaced(long newAddress, long oldAddress) { long oldSize = sizeCalculator.applyAsLong(oldAddress); long newSize = sizeCalculator.applyAsLong(newAddress); lruLock.lock(); try { removeNode(oldAddress); addEntryAddressToEnd(newAddress); currentSize += newSize; currentSize -= oldSize; // Must only remove entry while holding lru lock now super.entryReplaced(newAddress, oldAddress); } finally { lruLock.unlock(); } }
Source:
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { super.readFrom(input); onePhaseCommit = input.readBoolean(); retriedCommand = input.readBoolean(); START modifications = MarshallUtil.unmarshallArray(input, WriteCommand::array); END } Are prepare commands with 0 modifications that common?

Target:
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { super.readFrom(input); onePhaseCommit = input.readBoolean(); retriedCommand = input.readBoolean(); modifications = MarshallUtil.unmarshallArray(input, WriteCommand[]::new); }
Source:
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { timeoutMillis = input.readLong(); START chunk = MarshallUtil.unmarshallArray(input, XSiteState::array); END } Here too, I think 0-length arrays are quite rare (except maybe in tests that have little to no data in each segment).

Target:
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { timeoutMillis = input.readLong(); chunk = MarshallUtil.unmarshallArray(input, XSiteState[]::new); }
Source:
START protected <K> LocalStreamManager<K> waitUntilSendingResponse(final Cache<?, ?> cache, final CheckPoint checkPoint) { END return Mocks.blockingMock(checkPoint, LocalStreamManager.class, cache, (stub, m) -> stub.when(m).startIterator(any(), any(), any(), any(), any(), anyBoolean(), any(), anyLong())); } Can be void

Target:
protected <K> void waitUntilSendingResponse(final Cache<?, ?> cache, final CheckPoint checkPoint) { Mocks.blockingMock(checkPoint, LocalStreamManager.class, cache, (stub, m) -> stub.when(m).startIterator(any(), any(), any(), any(), any(), anyBoolean(), any(), anyLong())); }
Source:
START private static <K, V> CacheNotifier<K, V> blockNotifierPartitionStatusChanged(final CheckPoint checkPoint, END Cache<K, V> cache) { return Mocks.blockingMock(checkPoint, CacheNotifier.class, cache, (stub, m) -> stub.when(m).notifyPartitionStatusChanged(eq(AvailabilityMode.DEGRADED_MODE), eq(false))); } Can be void

Target:
private static <K, V> void blockNotifierPartitionStatusChanged(final CheckPoint checkPoint, Cache<K, V> cache) { Mocks.blockingMock(checkPoint, CacheNotifier.class, cache, (stub, m) -> stub.when(m).notifyPartitionStatusChanged(eq(AvailabilityMode.DEGRADED_MODE), eq(false))); }
Source:
public final Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { wrapEntryIfNeeded(ctx, command); START if (ctx.lookupEntry(command.getKey()) != null && ctx.lookupEntry(command.getKey()).getMetadata() instanceof L1Metadata) { END log.tracef("Put with L1 metadata"); } return setSkipRemoteGetsAndInvokeNextForDataCommand(ctx, command); } leftover from debugging?

Target:
public final Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { wrapEntryIfNeeded(ctx, command); return setSkipRemoteGetsAndInvokeNextForDataCommand(ctx, command); }
Source:
protected void assertPutFromLoadLatches(CountDownLatch[] latches) { START if (!await(latches[0]) && !await(latches[1])) END throw new AssertionError(String.format( "One of the latches in %s should have at least completed", Arrays.toString(latches))); } `assertTrue("One of...", await(latches[0]) || await(latches[1]));` ?

Target:
protected void assertPutFromLoadLatches(CountDownLatch[] latches) { assertTrue(String.format( "One of the latches in %s should have at least completed", Arrays.toString(latches)), await(latches[0]) || await(latches[1])); }
Source:
public void testRemoveFromNonOwner() { START for (Cache<Object, String> c : caches) assert c.isEmpty(); END Object retval = getFirstNonOwner("k1").put("k1", "value"); asyncWait("k1", PutKeyValueCommand.class); if (testRetVals) assert retval == null; retval = getOwners("k1")[0].remove("k1"); asyncWait("k1", RemoveCommand.class); if (testRetVals) assert "value".equals(retval); assertRemovedOnAllCaches("k1"); } I know this is not the purpose of your PR, but this test seems to me unnecessary as it is, unless it depends on DistSyncFuncTest instead of BaseDistFunctionalTest

Target:
public void testRemoveFromNonOwner() { Object retval = getFirstNonOwner("k1").put("k1", "value"); asyncWait("k1", PutKeyValueCommand.class); if (testRetVals) assert retval == null; retval = getOwners("k1")[0].remove("k1"); asyncWait("k1", RemoveCommand.class); if (testRetVals) assert "value".equals(retval); assertRemovedOnAllCaches("k1"); }
Source:
public Integer perform(InvocationContext ctx) throws Throwable { START long size = cache.getAdvancedCache().withEncoding(IdentityEncoder.class).keySet().stream().count(); END if (size > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else { return (int) size; } } It'd be better to decorate the cache in the constructor

Target:
public Integer perform(InvocationContext ctx) throws Throwable { long size = cache.keySet().stream().count(); if (size > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else { return (int) size; } }
Source:
public SizeCommand(Cache<Object, ?> cache, long flags) { setFlagsBitSet(flags); AdvancedCache<Object, ?> advancedCache = cache.getAdvancedCache(); if (flags != EnumUtil.EMPTY_BIT_SET) { advancedCache = advancedCache.withFlags(EnumUtil.enumArrayOf(flags, Flag.class)); } this.cache = advancedCache.getCacheConfiguration().memory().storageType() == StorageType.OBJECT ? START advancedCache : advancedCache.withEncoding(IdentityEncoder.class); END } FYI, this logic is part of https://github.com/infinispan/infinispan/pull/5329, to avoid creating new instances if the requested encoding is already in place

Target:
public SizeCommand(Cache<Object, ?> cache, long flags) { setFlagsBitSet(flags); AdvancedCache<Object, ?> advancedCache = cache.getAdvancedCache(); if (flags != EnumUtil.EMPTY_BIT_SET) { advancedCache = advancedCache.withFlags(EnumUtil.enumArrayOf(flags, Flag.class)); } this.cache = advancedCache.withEncoding(IdentityEncoder.class); }
Source:
public void startRemoteCache(RemoteCacheHolder remoteCacheHolder) { RemoteCacheImpl<?, ?> remoteCache = remoteCacheHolder.remoteCache; START OperationsFactory operationsFactory = new OperationsFactory( END transportFactory, remoteCache.getName(), remoteCacheHolder.forceReturnValue, codec, listenerNotifier, asyncExecutorService, configuration); remoteCache.init(marshaller, asyncExecutorService, operationsFactory, configuration.keySizeEstimate(), configuration.valueSizeEstimate(), configuration.batchSize()); } Do we really need this public? I would say to at least do package private if we can.

Target:
private void startRemoteCache(RemoteCacheHolder remoteCacheHolder) { RemoteCacheImpl<?, ?> remoteCache = remoteCacheHolder.remoteCache; OperationsFactory operationsFactory = new OperationsFactory( transportFactory, remoteCache.getName(), remoteCacheHolder.forceReturnValue, codec, listenerNotifier, asyncExecutorService, configuration); remoteCache.init(marshaller, asyncExecutorService, operationsFactory, configuration.keySizeEstimate(), configuration.valueSizeEstimate(), configuration.batchSize()); }
Source:
public void init(ComponentRegistry componentRegistry) { if (encodingClasses != null) { componentRegistry.wireDependencies(this); } START if (encodingClasses != null) { END componentRegistry.wireDependencies(this); } } wiring twice?

Target:
public void init(ComponentRegistry componentRegistry) { if (encodingClasses != null) { componentRegistry.wireDependencies(this); } }
Source:
public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable { if (isUsingAsyncStore(ctx, command)) { checkMarshallable(command.getKey()); START checkMarshallable(command.getFunction()); END } return invokeNext(ctx, command); } From the point of async store, it is not necessary to have the *function* serializable but the resulting entry. So the check does not belong here. The same holds for compute commands.

Target:
public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable { if (isUsingAsyncStore(ctx, command)) { checkMarshallable(command.getKey()); } return invokeNext(ctx, command); }
Source:
private Throwable getRootCauseException(Throwable re) { START if (re.getCause() == null) return re; END Throwable cause = re.getCause(); if (cause instanceof RuntimeException) return getRootCauseException(cause); else return re; } This works with or without this line :)

Target:
private Throwable getRootCauseException(Throwable re) { Throwable cause = re.getCause(); if (cause instanceof RuntimeException) return getRootCauseException(cause); else return re; }
Source:
private Collection<Address> getCommitNodes(TxInvocationContext ctx) { LocalTransaction localTx = (LocalTransaction) ctx.getCacheTransaction(); LocalizedCacheTopology cacheTopology = dm.getCacheTopology(); Collection<Address> affectedNodes = START isReplicated ? null : cacheTopology.getWriteOwners((Collection<Object>) ctx.getAffectedKeys()); END return localTx.getCommitNodes(affectedNodes, cacheTopology); } you don't need the cast

Target:
private Collection<Address> getCommitNodes(TxInvocationContext ctx) { LocalTransaction localTx = (LocalTransaction) ctx.getCacheTransaction(); LocalizedCacheTopology cacheTopology = dm.getCacheTopology(); Collection<Address> affectedNodes = isReplicated ? null : cacheTopology.getWriteOwners(ctx.getAffectedKeys()); return localTx.getCommitNodes(affectedNodes, cacheTopology); }
Source:
public <C> void addListener(Object listener, CacheEventFilter<? super K, ? super V> filter, START CacheEventConverter<? super K, ? super V, C> converter, ClassLoader classLoader) { END //TODO: add contracts for cache.getEncoder and cache.getWrapper addListenerInternal(listener, null, null, filter, converter, classLoader); } We still need to do this?

Target:
public <C> void addListener(Object listener, CacheEventFilter<? super K, ? super V> filter, CacheEventConverter<? super K, ? super V, C> converter, ClassLoader classLoader) { addListenerInternal(listener, null, null, null, null, filter, converter, classLoader); }
Source:
public DecoratedCache(AdvancedCache<K, V> delegate, Object lockOwner, Flag... flags) { super(delegate); if (flags == null) START throw new IllegalArgumentException("There is no point in using a DecoratedCache if Flags are set."); END if (flags.length == 0) this.flags = EnumUtil.EMPTY_BIT_SET; else { this.flags = EnumUtil.bitSetOf(flags); } this.lockOwner = lockOwner; // Yuk cacheImplementation = (CacheImpl<K, V>) delegate; } Hmm, can you call this ctor with `null` flags at all (besides using reflection)? If you don't specify any, it gets `new Flag[0]`, if you set `null` as last param, it will just get `null` flag...

Target:
public DecoratedCache(AdvancedCache<K, V> delegate, Object lockOwner, Flag... flags) { super(delegate); if (flags.length == 0) this.flags = EnumUtil.EMPTY_BIT_SET; else { this.flags = EnumUtil.bitSetOf(flags); } this.lockOwner = lockOwner; // Yuk cacheImplementation = (CacheImpl<K, V>) delegate; }
Source:
public CompletableFuture<Object> invokeAsync(InvocationContext ctx, VisitableCommand command) { START Stages.pushInvocationIdNDC(command, trace); END try { Object result = firstInterceptor.visitCommand(ctx, command); if (result instanceof InvocationStage) { return ((InvocationStage) result).toCompletableFuture(); } else { return CompletableFuture.completedFuture(result); } } catch (Throwable t) { return CompletableFutures.completedExceptionFuture(t); } finally { Stages.popInvocationIdNDC(command, trace); } } offtopic: doesn't seem related to the PR. are you trying to compete with Radim for the longest PR? :)

Target:
public CompletableFuture<Object> invokeAsync(InvocationContext ctx, VisitableCommand command) { try { Object result = firstInterceptor.visitCommand(ctx, command); if (result instanceof InvocationStage) { return ((InvocationStage) result).toCompletableFuture(); } else { return CompletableFuture.completedFuture(result); } } catch (Throwable t) { return CompletableFutures.completedExceptionFuture(t); } }
Source:
public int getViewId() { if (channel == null) throw new CacheException("The cache has been stopped and invocations are not allowed!"); START return (int) clusterView.getViewId(); END } no cast needed

Target:
public int getViewId() { if (channel == null) throw new CacheException("The cache has been stopped and invocations are not allowed!"); return clusterView.getViewId(); }
Source:
public void accept(Object rv, Throwable throwable) { // We started with a CompletableFuture, which is now complete. START if (trace) END log.tracef("Resuming invocation of command %s with %d handlers", command, queueSize()); Stages.pushInvocationIdNDC(command, trace); try { invokeQueuedHandlers(rv, throwable); } finally { Stages.popInvocationIdNDC(command, trace); } } IMO, the trace message was better in` invokeQueuedHandlers()`

Target:
public void accept(Object rv, Throwable throwable) { // We started with a CompletableFuture, which is now complete. invokeQueuedHandlers(rv, throwable); }
Source:
private Transaction getOngoingTransaction() { try { Transaction transaction = null; if (transactionManager != null) { transaction = transactionManager.getTransaction(); if (transaction == null && batchContainer != null) { transaction = batchContainer.getBatchTransaction(); } } return transaction; } catch (SystemException e) { throw new CacheException("Unable to get transaction", e); } START } END This is not implementing the correct pattern of dealing with transaction commit/rollback. [This code](https://github.com/infinispan/infinispan/blob/master/core/src/test/java/org/infinispan/test/TestingUtil.java#L1268) shows the correct pattern.

Target:
private Transaction getOngoingTransaction() { try { Transaction transaction = transactionManager.getTransaction(); if (transaction == null && batchContainer != null) { transaction = batchContainer.getBatchTransaction(); } return transaction; } catch (SystemException e) { throw new CacheException("Unable to get transaction", e); } }
Source:
public <T> ExecuteOperation<T> newExecuteOperation(String taskName, Map<String, byte[]> marshalledParams) { return new ExecuteOperation<>(codec, transportFactory, cacheNameBytes == null ? DEFAULT_CACHE_NAME_BYTES : cacheNameBytes, START topologyId, flags(), clientIntelligence, taskName, marshalledParams); END } Can we not assign `cacheNameBytes` to `DEFAULT_CACHE_NAME_BYTES` in the constructor if it was null instead and just always have this variable as non null?

Target:
public <T> ExecuteOperation<T> newExecuteOperation(String taskName, Map<String, byte[]> marshalledParams) { return new ExecuteOperation<>(codec, transportFactory, cacheNameBytes, topologyId, flags(), clientIntelligence, taskName, marshalledParams); }
Source:
public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) throws Throwable { START log.tracef("Processing a remote compute %s", command); END if (command.isConditional()) { return backupCache.computeIfPresent(command.getKey(), command.getRemappingBiFunction(), command.getMetadata()); } return backupCache.compute(command.getKey(), command.getRemappingBiFunction(), command.getMetadata()); } This trace message sticks out a bit. Thinking we should either remove or add logs to all the rest at some point.

Target:
public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) throws Throwable { if (command.isConditional()) { return backupCache.computeIfPresent(command.getKey(), command.getRemappingBiFunction(), command.getMetadata()); } return backupCache.compute(command.getKey(), command.getRemappingBiFunction(), command.getMetadata()); }
Source:
private boolean skipEncoding(Object source) { START return source == null || isTypeExcluded(source.getClass()); END } Hrmm, should this be needed? I wonder if this is a sign of something else being wrong.

Target:
private boolean skipEncoding(Object source) { return isTypeExcluded(source.getClass()); }
Source:
protected static CacheException handleMissingSuccessfulResponse(Map<Address, Response> responses) { if (responses.values().stream().anyMatch(UnsureResponse.class::isInstance)) { // We got only unsure responses, as all nodes that were read-owners at the time when we've sent // the request have progressed to newer topology. However we are guaranteed to have progressed // to a topology at most one older, and can immediately retry. return OutdatedTopologyException.getCachedInstance(); } else { // Another instance when we don't get any successful response is when all owners are lost. We'll handle // this later in StateTransferInterceptor, as we have to signal this to PartitionHandlingInterceptor // if that's present. return AllOwnersLostException.INSTANCE; START } END } I'd only throw `AllOwnersLostException` if the responses from all the target nodes are actually missing. If at least one owner threw an internal exception, I'd wrap that exception and return it to the caller. I'd also add a `getCachedInstance()` method to match `OutdatedTopologyException`. Thinking more about this, I'm not sure there is a point in having a separate `AllOwnersLostException`. `PartitionHandlingInterceptor` can do the partition check for all the `OutdatedTopologyException`s, and I think the performance impact would be minimal.

Target:
protected static CacheException handleMissingSuccessfulResponse(Map<Address, Response> responses) { // The response map does not contain any ExceptionResponses; these are rethrown as exceptions if (responses.values().stream().anyMatch(UnsureResponse.class::isInstance)) { // We got only unsure responses, as all nodes that were read-owners at the time when we've sent // the request have progressed to newer topology. However we are guaranteed to have progressed // to a topology at most one older, and can immediately retry. return OutdatedTopologyException.INSTANCE; } else { // Another instance when we don't get any successful response is when all owners are lost. We'll handle // this later in StateTransferInterceptor, as we have to signal this to PartitionHandlingInterceptor // if that's present. return AllOwnersLostException.INSTANCE; } }
Source:
public void onStateReceived(int segmentId, boolean isLastChunk) { if (!isCancelled && isLastChunk) { boolean isCompleted = false; synchronized (segments) { if (segments.contains(segmentId)) { START finishedSegments.add((Integer) segmentId); END if (finishedSegments.size() == segments.size()) { log.debugf("Finished receiving state for segments %s", segments); isCompleted = true; } } } if (isCompleted) { notifyCompletion(true); } } } not needed.

Target:
public void onStateReceived(int segmentId, boolean isLastChunk) { if (!isCancelled && isLastChunk) { boolean isCompleted = false; synchronized (segments) { if (segments.contains(segmentId)) { finishedSegments.add(segmentId); if (finishedSegments.size() == segments.size()) { log.debugf("Finished receiving state for segments %s", segments); isCompleted = true; } } } if (isCompleted) { notifyCompletion(true); } } }
Source:
public BasicCallbackHandler(String username, char[] password) { START this.username = username; END this.password = password; this.realm = null; } DRY: would use this(username, password, null) instead

Target:
public BasicCallbackHandler(String username, char[] password) { this(username, null, password); }
Source:
public <T> void onPostExecute(Callable<T> task) { try { BeanManager bm = CDIHelper.getBeanManager(); if (bm == null) return; postInject(bm, task); if(task instanceof DefaultExecutorService.RunnableAdapter) START { END postInject(bm, ((DefaultExecutorService.RunnableAdapter) task).getTask()); } } finally { ContextInputCache.clean(); } } Could you please use proper [formatter](https://github.com/infinispan/infinispan/tree/master/ide-settings)?

Target:
public <T> void onPostExecute(Callable<T> task) { try { BeanManager bm = CDIHelper.getBeanManager(); if (bm == null) return; postInject(bm, task); if (task instanceof RunnableAdapter) { postInject(bm, ((RunnableAdapter) task).getTask()); } } finally { ContextInputCache.clean(); } }