auphong2707/dl4se-code-review-dataset huggingface dataset:
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); if (checkView && !clusterView.contains(target)) return; send(message); }

Target:
Maybe this should be the first thing in the method?
Source:
public void startConflictResolution(ConsistentHash conflictCH, List<Address> mergeMembers) { topology = new CacheTopology(topology.getTopologyId() + 1, topology.getRebalanceId() + 1, conflictCH, conflictCH, conflictCH, CacheTopology.Phase.CONFLICT_RESOLUTION, mergeMembers, persistentUUIDs(mergeMembers)); }

Target:
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`?
Source:
synchronized void completeRequest() { List<Map<Address, CacheEntry<K, V>>> retVal = keyReplicaMap.entrySet().stream() .map(Map.Entry::getValue) .collect(Collectors.toList()); clear(); future.complete(Collections.unmodifiableList(retVal)); }

Target:
Could we get away with returning `keyReplicaMap.values()` here?
Source:
public CacheImpl(String name) { this.name = name; this.contextBuilder = this::getInvocationContextWithImplicitTransaction; this.pferContextBuilder = this::putForExternalReadContext; }

Target:
I would prefer to initialize these inline in field declaration rather than constructor... If I am not nitpicking too much...
Source:
public void onUpdate(CounterEvent event) { try { queue.put(event); log.tracef("[%s] add event %s", name, event); } catch (InterruptedException e) { log.errorf(e, "[%s] interrupted while adding event %s", name, event); } }

Target:
isTraceEnabled is not necessary here ?
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) && isKey == that.isKey; }

Target:
Putting ```isKey == that.isKey``` first will make the comparison fail faster :)
Source:
public boolean isReadable(int size) { return buffer.isReadable(); // see readableBytes(); }

Target:
should this be `buffer.isReadable(size)` ?
Source:
public Integer getNumberOfLocalConnections() { return Integer.valueOf(acceptedChannels.size()); }

Target:
Unnecessary boxing?
Source:
public SslConfiguration(boolean enabled, boolean requireClientAuth, Map<String, SslEngineConfiguration> sniDomainsConfiguration) { this.enabled = enabled; this.requireClientAuth = requireClientAuth; this.sniDomainsConfiguration = sniDomainsConfiguration; }

Target:
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?
Source:
static Configuration getCacheConfiguration(final AdvancedCache<?, ?> cache) { GetCacheConfigurationAction action = new GetCacheConfigurationAction(cache); return doPrivileged(action); }

Target:
```doPrivileged(cache::getCacheConfiguration)``` ?
Source:
void progress(String message, String color) { if (useColor) { progress(color + message + RESET); } else progress(message); }

Target:
Not using curly on the ```else``` branch? :)
Source:
public CacheQuery<E> sort(Sort sort) { this.sort = sort; this.queryDefinition.setSort(sort); return super.sort(sort); }

Target:
Is the ```sort``` field used at all? I see it being set but don't see it used anywhere.
Source:
public ClusteredQueryCommandWorker getCommand(Cache<?, ?> cache, QueryDefinition queryDefinition, UUID lazyQueryId, int docIndex) { ClusteredQueryCommandWorker command = null; command = getNewInstance(); command.init(cache, queryDefinition, lazyQueryId, docIndex); return command; }

Target:
Declaration and initialization of ```command``` can be done in same line.
Source:
public void inject(GlobalConfiguration globalConfiguration, EmbeddedCacheManager cacheManager) { this.globalConfiguration = globalConfiguration; this.cacheManager = cacheManager; this.localConfigurationManager = globalConfiguration.globalState().localConfigurationManager(); }

Target:
don't you want to create a factory for it? so it can be injected :)
Source:
public static MergePolicy fromConfiguration(EntryMergePolicy policy) { if (policy == null) return NONE; for (MergePolicy mp : MergePolicy.values()) if (mp.impl != null && Objects.equals(mp.impl.getClass(), policy.getClass())) return mp; return CUSTOM; }

Target:
If the enum implemented `EntryMergePolicy` directly, you could find the configured one with `mp == policy`.
Source:
private boolean resolveConflictsOnMerge(Configuration config, CacheMode cacheMode) { if (config == null || cacheMode.isScattered() || cacheMode.isInvalidation()) return false; ClusteringConfiguration cc = config.clustering(); return cc.partitionHandling().resolveConflictsOnMerge() && cc.hash().numOwners() > 1; }

Target:
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...
Source:
protected Object[] parameterValues() { String partitions = String.format("{%s, %s}", Arrays.toString(p0.getNodes()), Arrays.toString(p1.getNodes())); return concat(super.parameterValues(), partitions); }

Target:
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}`.
Source:
public boolean resolveConflictsOnMerge() { EntryMergePolicy policy = mergePolicy(); return (policy instanceof MergePolicy && policy != MergePolicy.NONE) || policy != null; }

Target:
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`.
Source:
void stop() { if (trace) log.tracef("Stop called on ReplicaSpliterator. Current segment %s", nextSegment); if (isConflictResolutionInProgress()) segmentRequestFuture.cancel(true); }

Target:
I think `stop()` could be called before any `tryAdvance()`, so I'd replace the condition with a `null` check on `segmentRequestFuture`.
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); if (keys == null) { segments = MarshallUtil.unmarshallIntCollection(input, SmallIntSet::new); } }

Target:
your luck is that the keys are never `null` otherwise you wouldn't be able to read the command.
Source:
protected CompletableFuture<?> completeSingleWriteOnPrimaryOriginator(DataWriteCommand command, Address backup, CompletableFuture<?> rpcFuture) { CompletableFuture<?> revokeFuture = revokeBiasSync(command.getKey(), backup, command.getTopologyId()); return revokeFuture == null ? rpcFuture : CompletableFuture.allOf(rpcFuture, revokeFuture); }

Target:
`revokeFuture` is never `null`
Source:
private static PathElement counterElement(ModelNode operation) throws OperationFailedException { final PathAddress address = pathAddress(operation.require(OP_ADDR)); final PathElement counterElement = address.getElement(address.size() - 1); return counterElement; }

Target:
`OperationFailedException` never thrown and it can be removed
Source:
public void stop(StopContext context) { // remove and destroy the counter instance EmbeddedCacheManager container = this.dependencies.getCacheContainer(); CounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager(container); counterManager.remove(counterConfigurationName); }

Target:
this is the cause of the persistent problem. you are deleting the counter from the persistent storage!
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 sizeCalculator = i -> offHeapEntryFactory.getSize(i) + OffHeapLruNode.getSize(); } this.lruLock = new ReentrantLock(); firstAddress = 0; }

Target:
Doesn't `offHeapEntryFactory.getSize()` include the size of the LRU pointers?
Source:
public void removeCache(CacheEntryRemovedEvent<ScopedState, CacheState> event) { String cacheName = event.getKey().getName(); gcm.log.debugf("Remove cache %s", cacheName); gcm.localRemoveCache(cacheName); }

Target:
Do we want a message for create as well?
Source:
public void removeCache(String cacheName) { authzHelper.checkPermission(AuthorizationPermission.ADMIN); if (cacheManagerAdmin != null) cacheManagerAdmin.removeCache(cacheName); else { RemoveCacheCommand.removeCache(this, cacheName); } }

Target:
I don't think the `cacheManagerAdmin` can be `null`
Source:
protected void entryReplaced(long newAddress, long oldAddress) { long oldSize = sizeCalculator.applyAsLong(oldAddress); long newSize = sizeCalculator.applyAsLong(newAddress); lruLock.lock(); try { if (trace) { log.tracef("Replacing LRU node: OldValue: 0x%016x NewValue: 0x%016x", oldAddress, 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(); } }

Target:
`removeNode` and `addEntryAddressToEnd` both log, so maybe we can remove this log ,essage.
Source:
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { super.readFrom(input); onePhaseCommit = input.readBoolean(); retriedCommand = input.readBoolean(); modifications = MarshallUtil.unmarshallArray(input, WriteCommand::array); }

Target:
Are prepare commands with 0 modifications that common?
Source:
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { timeoutMillis = input.readLong(); chunk = MarshallUtil.unmarshallArray(input, XSiteState::array); }

Target:
Here too, I think 0-length arrays are quite rare (except maybe in tests that have little to no data in each segment).
Source:
protected <K> LocalStreamManager<K> waitUntilSendingResponse(final Cache<?, ?> cache, final CheckPoint checkPoint) { return Mocks.blockingMock(checkPoint, LocalStreamManager.class, cache, (stub, m) -> stub.when(m).startIterator(any(), any(), any(), any(), any(), anyBoolean(), any(), anyLong())); }

Target:
Can be void
Source:
private static <K, V> CacheNotifier<K, V> blockNotifierPartitionStatusChanged(final CheckPoint checkPoint, Cache<K, V> cache) { return Mocks.blockingMock(checkPoint, CacheNotifier.class, cache, (stub, m) -> stub.when(m).notifyPartitionStatusChanged(eq(AvailabilityMode.DEGRADED_MODE), eq(false))); }

Target:
Can be void
Source:
public final Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { wrapEntryIfNeeded(ctx, command); if (ctx.lookupEntry(command.getKey()) != null && ctx.lookupEntry(command.getKey()).getMetadata() instanceof L1Metadata) { log.tracef("Put with L1 metadata"); } return setSkipRemoteGetsAndInvokeNextForDataCommand(ctx, command); }

Target:
leftover from debugging?
Source:
protected void assertPutFromLoadLatches(CountDownLatch[] latches) { if (!await(latches[0]) && !await(latches[1])) throw new AssertionError(String.format( "One of the latches in %s should have at least completed", Arrays.toString(latches))); }

Target:
`assertTrue("One of...", await(latches[0]) || await(latches[1]));` ?
Source:
public void testRemoveFromNonOwner() { for (Cache<Object, String> c : caches) assert c.isEmpty(); 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"); }

Target:
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
Source:
public Integer perform(InvocationContext ctx) throws Throwable { long size = cache.getAdvancedCache().withEncoding(IdentityEncoder.class).keySet().stream().count(); if (size > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else { return (int) size; } }

Target:
It'd be better to decorate the cache in the constructor
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 ? advancedCache : advancedCache.withEncoding(IdentityEncoder.class); }

Target:
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
Source:
public 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()); }

Target:
Do we really need this public? I would say to at least do package private if we can.
Source:
public void init(ComponentRegistry componentRegistry) { if (encodingClasses != null) { componentRegistry.wireDependencies(this); } if (encodingClasses != null) { componentRegistry.wireDependencies(this); } }

Target:
wiring twice?
Source:
public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable { if (isUsingAsyncStore(ctx, command)) { checkMarshallable(command.getKey()); checkMarshallable(command.getFunction()); } return invokeNext(ctx, command); }

Target:
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.
Source:
private Throwable getRootCauseException(Throwable re) { if (re.getCause() == null) return re; Throwable cause = re.getCause(); if (cause instanceof RuntimeException) return getRootCauseException(cause); else return re; }

Target:
This works with or without this line :)
Source:
private Collection<Address> getCommitNodes(TxInvocationContext ctx) { LocalTransaction localTx = (LocalTransaction) ctx.getCacheTransaction(); LocalizedCacheTopology cacheTopology = dm.getCacheTopology(); Collection<Address> affectedNodes = isReplicated ? null : cacheTopology.getWriteOwners((Collection<Object>) ctx.getAffectedKeys()); return localTx.getCommitNodes(affectedNodes, cacheTopology); }

Target:
you don't need the cast
Source:
public <C> void addListener(Object listener, CacheEventFilter<? super K, ? super V> filter, CacheEventConverter<? super K, ? super V, C> converter, ClassLoader classLoader) { //TODO: add contracts for cache.getEncoder and cache.getWrapper addListenerInternal(listener, null, null, filter, converter, classLoader); }

Target:
We still need to do this?
Source:
public DecoratedCache(AdvancedCache<K, V> delegate, Object lockOwner, Flag... flags) { super(delegate); if (flags == null) throw new IllegalArgumentException("There is no point in using a DecoratedCache if Flags are set."); 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; }

Target:
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...
Source:
public CompletableFuture<Object> invokeAsync(InvocationContext ctx, VisitableCommand command) { Stages.pushInvocationIdNDC(command, trace); 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); } }

Target:
offtopic: doesn't seem related to the PR. are you trying to compete with Radim for the longest PR? :)
Source:
public int getViewId() { if (channel == null) throw new CacheException("The cache has been stopped and invocations are not allowed!"); return (int) clusterView.getViewId(); }

Target:
no cast needed
Source:
public void accept(Object rv, Throwable throwable) { // We started with a CompletableFuture, which is now complete. if (trace) 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); } }

Target:
IMO, the trace message was better in` invokeQueuedHandlers()`
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); } }

Target:
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.
Source:
public <T> ExecuteOperation<T> newExecuteOperation(String taskName, Map<String, byte[]> marshalledParams) { return new ExecuteOperation<>(codec, transportFactory, cacheNameBytes == null ? DEFAULT_CACHE_NAME_BYTES : cacheNameBytes, topologyId, flags(), clientIntelligence, taskName, marshalledParams); }

Target:
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?
Source:
public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) throws Throwable { log.tracef("Processing a remote compute %s", command); if (command.isConditional()) { return backupCache.computeIfPresent(command.getKey(), command.getRemappingBiFunction(), command.getMetadata()); } return backupCache.compute(command.getKey(), command.getRemappingBiFunction(), command.getMetadata()); }

Target:
This trace message sticks out a bit. Thinking we should either remove or add logs to all the rest at some point.
Source:
private boolean skipEncoding(Object source) { return source == null || isTypeExcluded(source.getClass()); }

Target:
Hrmm, should this be needed? I wonder if this is a sign of something else being wrong.
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; } }

Target:
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.
Source:
public void onStateReceived(int segmentId, boolean isLastChunk) { if (!isCancelled && isLastChunk) { boolean isCompleted = false; synchronized (segments) { if (segments.contains(segmentId)) { finishedSegments.add((Integer) segmentId); if (finishedSegments.size() == segments.size()) { log.debugf("Finished receiving state for segments %s", segments); isCompleted = true; } } } if (isCompleted) { notifyCompletion(true); } } }

Target:
not needed.
Source:
public BasicCallbackHandler(String username, char[] password) { this.username = username; this.password = password; this.realm = null; }

Target:
DRY: would use this(username, password, null) instead
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) { postInject(bm, ((DefaultExecutorService.RunnableAdapter) task).getTask()); } } finally { ContextInputCache.clean(); } }

Target:
Could you please use proper [formatter](https://github.com/infinispan/infinispan/tree/master/ide-settings)?
Source:
protected final Object handleMissingEntryOnRead(TopologyAffectedCommand command) { // If we have the entry in context it means that we are read owners, so we don't have to check the topology CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); int currentTopologyId = cacheTopology.getTopologyId(); int cmdTopology = command.getTopologyId(); if (cmdTopology < currentTopologyId) { return (Object) UnsuccessfulResponse.INSTANCE; } else { // If cmdTopology > currentTopologyId: the topology of this node is outdated // TODO: This situation won't happen as soon as we'll implement 4-phase topology change in ISPN-5021 // (then, Tx.readCH and T(x+1).readCH will always have common subset of nodes so we'll be safe here // to return UnsuccessfulResponse // If cmdTopology == currentTopologyId: between STI and BDI this node had different topology, therefore // the entry was not loaded into context. Retry again locally. throw new OutdatedTopologyException(cmdTopology); } }

Target:
unnecessary cast
Source:
public void testThrowingNullPointerExceptionOnNullGetWithClass() throws Exception { //when cache.get(null, (Class<Object>) null); }

Target:
Shouldn't that be `Class<?>`
Source:
protected boolean addHandler(InvocationComposeHandler composeHandler) { synchronized (this) { if (frozen) { return false; } handlers[tail & mask] = composeHandler; if (((tail + 1 - head) & mask) == 0) { frozen = true; return false; } tail++; return true; } }

Target:
You've managed to add the handler, why are you returning `false`?
Source:
String readString() { byte mark = readByte(); switch(mark) { case 0: return ""; // empty string case 1: // small ascii int size = readByte(); String str = new String(bytes, 0, pos, size); pos += size; return str; case 2: // large string return readUTF(); case 3: default: throw new RuntimeException("Unknown marker(String). mark=" + mark); } }

Target:
Case 3 is redundant
Source:
private static int checkForeignIdLimit(int id, AdvancedExternalizer<?> ext) { if (id < 0) throw log.foreignExternalizerUsingNegativeId(ext, id); return id; }

Target:
As no transformations are happening to id, why not make `checkForeignIdLimit` void
Source:
BiConsumer<ObjectOutput, Object> findWriter(Object obj) { Class<?> clazz = obj.getClass(); AdvancedExternalizer internalExt = internalExts.get(clazz); if (internalExt != null) return (out, object) -> { writeInternalClean(object, internalExt, out); }; AdvancedExternalizer externalExt = externalExts.get(clazz); if (externalExt != null) return (out, object) -> { writeExternalClean(object, externalExt, out); }; return null; }

Target:
Can be reduced to a single line lambda
Source:
public long skip(long n) { if (n > 0) { long skip = bytes.length - pos; if (skip < pos) skip = n; pos += skip; return skip; } else { int idx = Math.min(bytes.length, pos); long skip = idx + n; pos = (int) (skip + offset); return skip; } }

Target:
shouldn't be `skip > n`?
Source:
public void clear() { Arrays.fill(keys, null); count = 0; }

Target:
shouldn't the `values` be fill with `null`? (to help GC)
Source:
void beforeSplit() { conflictKey = new MagicKey(cache(2), cache(0)); System.out.println(advancedCache(0).getCacheConfiguration().clustering().partitionHandling().getMergePolicy()); cache(0).put(conflictKey, "BEFORE SPLIT"); }

Target:
System.out
Source:
public MergePolicyCustomTest() { super(); this.mergePolicy = ((preferredEntry, otherEntries) -> TestInternalCacheEntryFactory.create(conflictKey, "Custom")); }

Target:
redundant
Source:
public ConsistentHash getReadConsistentHash() { switch (phase) { case CONFLICT_RESOLUTION: assert pendingCH != null; assert unionCH != null; return currentCH; case NO_REBALANCE: assert pendingCH == null; assert unionCH == null; return currentCH; case READ_OLD_WRITE_ALL: assert pendingCH != null; assert unionCH != null; return currentCH; case READ_ALL_WRITE_ALL: assert pendingCH != null; return unionCH; case READ_NEW_WRITE_ALL: assert unionCH != null; return pendingCH; } return currentCH; }

Target:
Just move the label before READ_OLD_WRITE_ALL, it has the same properties.
Source:
private Stream<Map<Address, CacheEntry<K, V>>> getConflicts(LocalizedCacheTopology topology) { if (stateConsumer.isStateTransferInProgress()) throw log.getConflictsStateTransferInProgress(cacheName); if (!streamInProgress.compareAndSet(false, true)) throw log.getConflictsAlreadyInProgress(); try { return StreamSupport .stream(new ReplicaSpliterator(topology), false) .filter(filterConsistentEntries()); } finally { streamInProgress.compareAndSet(true, false); } }

Target:
You're returning the stream itself; no terminal operation was called so far on the stream, so it's still in progress, isn't it?
Source:
private String sanitizedCacheName() { String cacheFileName = ctx.getCache().getName().replaceAll("[^a-zA-Z0-9-_\\.]", "_"); return cacheFileName; }

Target:
`cacheFileName` variable is redundant
Source:
public void generateValidMoves() { validMoves = new String[operations]; for (int i = 0; i < operations; i++) { validMoves[i] = "v_" + i; } print("Valid moves ready"); }

Target:
`operations` is initialized in the constructor, you could also initialize `validMoves` the same way.
Source:
private static Class<Map> getMapClass(String className) { return Util.<Map>loadClass(className, Map.class.getClassLoader()); }

Target:
I think this should return a `Class<? extends Map>`.
Source:
public ClusterEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new ClusterEvent(input.readObject(), input.readObject(), input.readObject(), (Metadata)input.readObject(),(Type) MarshallUtil.unmarshallEnum(input, Type::valueOf), (Address)input.readObject(), (GlobalTransaction)input.readObject(), input.readBoolean()); }

Target:
unneeded cast :)
Source:
public TransactionInfo readObject(ObjectInput input) throws IOException, ClassNotFoundException { GlobalTransaction globalTransaction = (GlobalTransaction) input.readObject(); int topologyId = input.readInt(); WriteCommand[] modifications = MarshallUtil.unmarshallArray(input, WriteCommand[]::new); Set<Object> lockedKeys = (Set<Object>) MarshallUtil.unmarshallCollection(input, HashSet::new); return new TransactionInfo(globalTransaction, topologyId, modifications, lockedKeys); }

Target:
unneeded cast
Source:
public void testGetCacheNames() { Boolean passed = StreamSupport.stream(cacheManager.getCacheNames().spliterator(), true) .anyMatch(n -> getCacheNamesTestCacheName.equalsIgnoreCase(n)); assertTrue(getCacheNamesTestCacheName + " cache name was not found in list retrieved from CacheManager", passed); }

Target:
`boolean` should work
Source:
public void writeTo(ObjectOutput output) throws IOException { output.writeObject(key); output.writeInt(topologyId); output.writeLong(Flag.copyWithoutRemotableFlags(getFlagsBitSet())); }

Target:
the `topologyId` is written/read in the `ReplicableCommandExternalizer`. no need to write/read it again.
Source:
public boolean lock(K... keys) { return cacheImplementation.lock(Arrays.asList(keys), flags, null); }

Target:
The methods with ClassLoader are package-private, therefore non-public API - can't you remove the parameter altogether?
Source:
public ClusteredCacheQueryImpl(Query luceneQuery, SearchIntegrator searchFactory, ExecutorService asyncExecutor, AdvancedCache<?, ?> cache, KeyTransformationHandler keyTransformationHandler, Class<?>... classes) { super(luceneQuery, searchFactory, cache, keyTransformationHandler, classes); this.asyncExecutor = asyncExecutor; this.hSearchQuery = searchFactory.createHSQuery().luceneQuery(luceneQuery) .targetedEntities(Arrays.asList(classes)); this.marshaller = ComponentRegistryUtils.getComponent(cache, StreamingMarshaller.class); }

Target:
not related to your changes, but it looks like this field is not used anymore.
Source:
public InputStream lookupFileStrict(URI uri, ClassLoader cl) throws FileNotFoundException { //in case we have not only file schema, but jar:file schema too, we have to get rid off all schemas int startIndex = uri.toString().lastIndexOf(':'); String fileName = uri.toString().substring(startIndex + 1); InputStream in = cl.getResourceAsStream(fileName); if(in != null){ return in; } else { return null; } }

Target:
You could just `return cl.getResourceAsStream(fileName);`
Source:
default void waitForTransactionData(int expectedTopologyId, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { try { CompletableFuture<Void> transactionDataFuture = transactionDataFuture(expectedTopologyId); if (transactionDataFuture != null) transactionDataFuture.get(timeout, unit); } catch (ExecutionException e) { throw new CacheException(e.getCause()); } }

Target:
This isn't an SPI, so I'm not sure it's worth putting the implementation in the interface.
Source:
private ClientAuth requireClientAuth(SslConfiguration sslConfig) { return sslConfig.enabled() ? ClientAuth.REQUIRE : ClientAuth.NONE; }

Target:
This should be `sslConfig.requireClientAuth()` ;) TL;DR After turning on [SSL Debug](https://blogs.oracle.com/java-platform-group/entry/diagnosing_tls_ssl_and_https) it turned out that server challenges client for certificate (which was not associated with the client keystore). This suggested that either client cert file is wrong or server challenge is wrong. I was lucky with the latter :)
Source:
public int compareTo(Address o) { return 0; }

Target:
Hrmm, maybe this return 0 only if `o == this`? Otherwise maybe `o.compareTo(this)` to ensure symmetry ?
Source:
protected void errorOccurred(ErrorContext context) { if (operationFailedHandler == null) { throw new IllegalStateException("Uninitialised error handler"); } Throwable throwable = context.getThrowable(); if (throwable instanceof LockObtainFailedException) { List<LuceneWork> failingOperations = context.getFailingOperations(); LuceneWork operationAtFault = context.getOperationAtFault(); List<LuceneWork> failed = new ArrayList<>(failingOperations); failed.add(operationAtFault); operationFailedHandler.lockObtainFailed(failed); } }

Target:
Should this log a debug as well? An error sounds important :)
Source:
public synchronized void stop(final StopContext context) { router.ifPresent(r -> r.stop()); }

Target:
should be able to pass `r::stop`.
Source:
public SaslConfigurationBuilder forCredentials(String login, String password) { this.security().authentication().callbackHandler(new SimpleLoginHandler(login, password, Constants.DEFAULT_TEST_REALM)); return this; }

Target:
`Constants` is a way too generic name, have a look at https://github.com/infinispan/infinispan/blob/master/server/integration/endpoint/src/main/java/org/infinispan/server/endpoint/Constants.java#L57 to see what happens when you name a class like that :) You can leave the constants here, and just make them public.
Source:
public String getPort() { return nettyPort.orElse(address.getPort()).toString(); }

Target:
Can't you use just `address.getPort()`?
Source:
public void stop() { netty.ifPresent(NettyJaxrsServer::stop); netty = Optional.empty(); server = Optional.empty(); }

Target:
Don't you need `server.get().stop()` as well?
Source:
public MultiTenantRouter(MultiTenantRouterConfiguration routerConfiguration) { this.routerConfiguration = routerConfiguration; routerConfiguration.getHotRodRouterConfiguration().ifPresent(config -> routers.add(new HotRodRouter(config))); routerConfiguration.getRestRouterConfiguration().ifPresent(config -> routers.add(new RestRouter(config))); }

Target:
I think it would be simpler to store each router in a separate field.
Source:
public void testWeldStandaloneInitialisation() throws Exception { //given WeldContainer weld = new Weld().initialize(); CDITestingBean testedBean = weld.instance().select(CDITestingBean.class).get(); //when testedBean.putValueInCache("test", "abcd"); String retrievedValue = testedBean.getValueFromCache("test"); //then assertEquals(retrievedValue, "abcd"); //cleanup weld.shutdown(); }

Target:
Shouldn't this be in a `finally` block?
Source:
protected boolean interceptorMatches(AsyncInterceptor interceptor, Class<? extends AsyncInterceptor> clazz) { Class<? extends AsyncInterceptor> interceptorType = interceptor.getClass(); return clazz == interceptorType; }

Target:
can be private
Source:
public CompletableFuture<Void> visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { ctx.onReturn(writeSkewReturnHandler); if (streamSummaryContainer.isEnabled() && ctx.isOriginLocal()) { streamSummaryContainer.addPut(command.getKey(), isRemote(command.getKey())); } return ctx.continueInvocation(); }

Target:
you could move the `if` before `ctx.onReturn()` and avoid invoking `ctx.continueInvocation()`
Source:
private boolean isSniEnabled() { return sniDomains.keySet().size() > 0; }

Target:
return !sniDomains.isEmpty();
Source:
public void serialize(XMLExtendedStreamWriter writer, RemoteStoreConfiguration configuration) throws XMLStreamException { AttributeSet attributes = configuration.attributes(); writer.writeStartElement(Element.REMOTE_STORE); writeCommonStoreSubAttributes(writer, configuration); writeAsyncExecutor(writer, configuration.asyncExecutorFactory()); writeConnectionPool(writer, configuration.connectionPool()); writeServers(writer, configuration.servers()); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }

Target:
did you forget to serialize the attributes?
Source:
public void serialize(XMLExtendedStreamWriter writer, JdbcStringBasedStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.STRING_KEYED_JDBC_STORE); writeJdbcStoreAttributes(writer, configuration); configuration.attributes().write(writer, JdbcStringBasedStoreConfiguration.KEY2STRING_MAPPER, Attribute.KEY_TO_STRING_MAPPER); writeCommonStoreSubAttributes(writer, configuration); writeJDBCStoreTable(writer, Element.STRING_KEYED_TABLE, configuration.table()); writeJDBCStoreConnection(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }

Target:
`writeJdbcStoreAttributes` already writes this attribute.
Source:
public Builder autoPersist(boolean autoPersist) { this.autoPersist = autoPersist; return this; }

Target:
generics is missing
Source:
public String toString() { return new String(b, CHARSET); }

Target:
I'm a little concern about this. wouldn't be better to cache the string too?
Source:
public VersionedCommitCommand() { super(ByteString.emptyString()); }

Target:
Might as well use `null`, almost all commands use `super(null)` in the "CommandIdUniquenessTest constructor".
Source:
public void testOnlyReduceTaskRun() throws Exception { ScriptingManager scriptingManager = getScriptingManager(manager(0)); Cache<String, String> cache = cache(0); loadData(cache, "/macbeth.txt"); loadScript(scriptingManager, "/wordCountReducer.js"); CompletableFuture<Object> future = scriptingManager.runScript("wordCountReducer.js", new TaskContext().cache(cache)); }

Target:
Could you tell me which line throws `IllegalArgumentException`? Maybe we need do something with this `CompletableFuture` here?
Source:
public void grant(String roleName, String principalName) { Set<String> roleSet = getClusterRoleMap().computeIfAbsent(principalName, n -> { return new HashSet<>(); }); roleSet.add(roleName); clusterRoleMap.put(principalName, roleSet); }

Target:
replace `{ return new HashSet<>(); }` with `new HashSet<>()` ?
Source:
public void testTask() throws Exception { ScriptingManager scriptingManager = cacheManager.getGlobalComponentRegistry().getComponent(ScriptingManager.class); ScriptingTest.loadScript(scriptingManager, TEST_SCRIPT); String result = (String) taskManager.runTask(TEST_SCRIPT, new TaskContext().addParameter("a", "a")).get(); assertEquals("a", result); }

Target:
Maybe move this method to a separate `ScriptingTests` class.
Source:
private TaskContext prepareContext() { TaskContext context = new TaskContext(); if (parameters != null) context.parameters(parameters); if (cache != null) context.cache(cache); Marshaller marshaller = componentRegistry.getComponent(Marshaller.class); if (marshaller != null) context.marshaller(marshaller); return context; }

Target:
You can use `Optional.ofNullable(...).ifPresent(...) or flatMap` constructs here.
Source:
public T call() throws Exception { ServerTaskRegistry taskRegistry = componentRegistry.getComponent(ServerTaskRegistry.class); ServerTaskWrapper<T> task = taskRegistry.getTask(taskName); task.inject(prepareContext()); return task.run(); }

Target:
I think the ServerTaskRegistry should not be obtained here, but it should be injected by the runner during construction. Also, a cache is optional paramater in the TaskContext and you should not rely on its presence here. Because of a current limitation in the DefaultExecutorService, it is not possible to have a distexec without a distributed cache, but @wburns is adding a new implementation which changes this.
Source:
public String getGroup(Object instance) { PrivilegedAction<Object> action = () -> invokeAccessibly(instance, method, Util.EMPTY_OBJECT_ARRAY); Object object = System.getSecurityManager() == null ? action.run() : AccessController.doPrivileged(action); return String.class.cast(object); }

Target:
Instead of always invoking the lambda like that I'd rather do if (System.getSecurityManager() == null) { return String.class.cast(invokeAccessibly(instance, method, Util.EMPTY_OBJECT_ARRAY)); } else { ... // priv action }
Source:
protected void mergeCluster(String cacheName) { getLog().debugf("Merging cluster"); partition(0).merge(partition(1)); TestingUtil.waitForRehashToComplete(caches(cacheName)); getLog().debugf("Cluster merged"); }

Target:
you can remove the `TestingUtil.` prefix and the import
Source:
public void writeObject(ObjectOutput output, ScriptMetadata object) throws IOException { output.writeUTF(object.name); output.writeUTF(object.extension); output.writeUTF(object.mode.name()); writeSet(output, object.parameters); output.writeObject(object.language); output.writeObject( object.role); output.writeObject(object.reducer); output.writeObject(object.collator); output.writeObject(object.combiner); }

Target:
Extra space.
Source:
protected boolean interceptorMatches(SequentialInterceptor interceptor, Class<? extends SequentialInterceptor> clazz) { Class<? extends SequentialInterceptor> interceptorType = interceptor.getClass(); return clazz == interceptorType || clazz == interceptorType; }

Target:
duplicated condition.
Source:
public void writeScopedState(ScopedPersistentState state) { File stateFile = getStateFile(state.getScope()); try (PrintWriter w = new PrintWriter(stateFile)) { state.forEach((key, value) -> { w.printf("%s=%s%n", key, Util.unicodeEscapeString(value)); }); } catch (IOException e) { throw log.failedWritingGlobalState(e, stateFile); } }

Target:
I think the key should be escaped as well.
Source:
public void forEach(IntConsumer action) { if (action instanceof CacheAware) { ((CacheAware) action).injectCache(registry.getComponent(Cache.class)); } createStream().forEach(action); }

Target:
why not factor out this code ? It's repeated in quite a few places.
Source:
public void checkPermission(AuthorizationPermission perm) { checkPermission(null, perm, Optional.empty()); }

Target:
I don't really like mixing `Optional` with old-style nullable parameters, so I'd rather use `null` for both. (Or `Optional` for both, of course.)
Source:
public void appendDelta(Delta d) { deltas.add(d); if (uncommittedChanges instanceof AtomicHashMap) { uncommittedChanges = (AtomicHashMap<K, ?>) d.merge(uncommittedChanges); } setChanged(true); }

Target:
this condition is always true.
Source:
public MVCCEntry wrapEntryForPut(InvocationContext ctx, Object key, InternalCacheEntry icEntry, boolean undeleteIfNeeded, FlagAffectedCommand cmd, boolean skipRead) { if (icEntry != null) { throw new IllegalArgumentException("Only addMissingValue can handle external entries"); } MVCCEntry mvccEntry = wrapEntryForWriting(ctx, key, Wrap.WRAP_ALL, skipRead, false); if (trace) { log.tracef("Wrap %s for put. Entry=%s", key, mvccEntry); } return mvccEntry; }

Target:
wrong method name?
Source:
public static void attemptObtain(ObtainableLock lock) throws IOException { int attempts = 0; while (lock.obtain()==false) { //we could fail immediately, but being Infinispan a bit latency sensitive we give a bit of grace here if (attempts++>MAX_LOCK_ACQUIRE_MILLISECONDS) failLockAcquire(); if (Thread.currentThread().isInterrupted()) failLockAcquire(); try { Thread.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); failLockAcquire(); } } }

Target:
I'll change it
Source:
public void testSimpleExpirationMaxIdle() throws Exception { for (int i = 0; i < SIZE; i++) { cache.put("key-" + i, "value-" + i,-1, TimeUnit.MILLISECONDS, 1, TimeUnit.MILLISECONDS); } timeService.advance(2); assertEquals(0, cache.size()); }

Target:
I believe the problem should be addressed in the Metadata implementation. Negative time values should not be converted, so the given TimeUnit could be null and not result in an exception.
Source:
public static void assertNotNullEntries(Collection<?> collection, String name) { Objects.requireNonNull(collection, () -> "Collection '" + name + "' must be non null."); Supplier<String> entrySupplier = () -> "Collection '" + name + "' contains null entry."; collection.forEach((k) -> Objects.requireNonNull(k, entrySupplier)); }

Target:
Nitpick here, but parens aren't required around the k.
Source:
public static Set<Flag> addFlag(Set<Flag> flags, Flag newFlag) { if (flags == null) { return EnumSet.of(newFlag); } if (flags.contains(newFlag)) { return flags; } EnumSet<Flag> copy = EnumSet.copyOf(flags); copy.add(newFlag); return copy; }

Target:
:+1: this is a lot nicer than before
Source:
public void setParameters(int commandId, Object[] args) { // TODO: Check duplicated in all commands? A better solution is needed. if (commandId != COMMAND_ID) throw new IllegalStateException("Unsupported command id:" + commandId); int i = 0; globalTx = (GlobalTransaction) args[i++]; unlock = (Boolean) args[i++]; keys = (List<Object>) args[i++]; flags = (EnumSet<Flag>) args[i]; }

Target:
This change seems unneeded, did you want to change the declared type of flags as well? Otherwise I could see someone possibly passing in the wrong set impl.
Source:
public static Set<Flag> addFlags(Set<Flag> flags, Set<Flag> newFlags) { if (newFlags == null || newFlags.isEmpty()) { return flags; } if (flags == null) { return newFlags; } EnumSet<Flag> copy = EnumSet.copyOf(flags); copy.addAll(newFlags); return copy; }

Target:
or flags.isEmpty?
Source:
public static <T> void forEach(T[] array, Consumer<T> consumer) { Objects.requireNonNull(array, "Array must be non-null."); final int size = array.length; if (size == 0) { return; } else if (size == 1) { consumer.accept(array[0]); return; } for (int i = 0; i < size; ++i) { consumer.accept(array[i]); } }

Target:
I think only the for loop should be good enough - there's no allocation, and it will do the same `0 < size`, `1 < size` comparisons.
Source:
private void invoke(LockListener invoker) { LockState state = lockState; switch (state) { case WAITING: throw new IllegalStateException("WAITING is not a valid state to invoke the listener"); case ACQUIRED: case RELEASED: invoker.onEvent(LockState.AVAILABLE); break; default: invoker.onEvent(state); break; } }

Target:
This looks weird to me, why shouldn't the listener receive the actual state?
Source:
private boolean setReleased() { do { LockState state = lockState; switch (state) { case WAITING: case AVAILABLE: case ACQUIRED: if (casState(state, LockState.RELEASED)) { cleanup(); notifyListeners(); return true; } break; case TIMED_OUT: case DEADLOCKED: if (casState(state, LockState.RELEASED)) { cleanup(); return true; } break; default: return false; } } while (true); }

Target:
Is it ok to go from WAITING straight to RELEASED?
Source:
public void testGroupBy3() throws Exception { QueryFactory qf = getQueryFactory(); Query q = qf.from(getModelFactory().getUserImplClass()) .select("name") .groupBy("name") .orderBy("surname", SortOrder.ASC) .build(); q.list(); }

Target:
What about doing aggregation in a filtered query? Would something conceptually similar to `SELECT name FROM person WHERE name.startsWith("a") GROUP BY name` work? It seems there is no test for it
Source:
public void update(Object[] srcRow, Object[] destRow) { Number value = (Number) srcRow[pos]; if (value != null) { Number sum = (Number) destRow[pos]; if (sum == null) { destRow[pos] = value; } else { destRow[pos] = sum.intValue() + value.intValue(); //todo [anistor] this handles integers only! } } }

Target:
I would say we should use a long and double respectively.
Source:
public ControllerThread(String controllerThreadName) { super(controllerThreadName); readyList = new LinkedList<>(); semaphore = new Semaphore(0); }

Target:
I normally prefer ArrayDeque over LinkedList since we aren't adding/removing elements from the middle
Source:
public static int writeUnsignedInt(byte[] bytes, int offset, int i) { int localOffset = offset; while ((i & ~0x7F) != 0) { bytes[localOffset++] = (byte) ((i & 0x7f) | 0x80); i >>>= 7; } bytes[localOffset] = (byte) i; return localOffset + 1; }

Target:
:+1: I am surprised we didn't have this before I wonder if returning the size used may be better, WDYT?
Source:
protected boolean beforeInvoke() throws Exception { if (0 <= commandTopologyId && commandTopologyId < handler.stateTransferManager.getFirstTopologyAsMember()) { if (handler.isTraceEnabled()) { handler.getLog().tracef("Ignoring command sent before the local node was a member " + "(command topology id is %d)", commandTopologyId); } response = CacheNotFoundResponse.INSTANCE; return false; //skip invocation } return true; }

Target:
I wonder if making this more explicit would be cleaner. What if the beforeInvoke method declaration was changed to return a Response. If that value was null it would be considered to continue running and if not null it would return that response? WDYT?
Source:
public void start() { isPessimisticCache = cacheConfiguration.transaction().lockingMode() == LockingMode.PESSIMISTIC; useClusteredWriteSkewCheck = Configurations.isVersioningEnabled(cacheConfiguration); rollbackRpcOptions = createRpcOptionsFor2ndPhase(cacheConfiguration.transaction().syncRollbackPhase() ); commitRpcOptions = createRpcOptionsFor2ndPhase(cacheConfiguration.transaction().syncCommitPhase() ); }

Target:
Line wrap is a bit weird here