auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START private boolean hasDeadlineExpired(final Date deadline) { END if (deadline != null) { return System.currentTimeMillis() > deadline.getTime(); } else { return false; } } It seems like these two deadline-related methods could be `static`.

Target:
private static boolean hasDeadlineExpired(final Date deadline) { if (deadline != null) { return System.currentTimeMillis() > deadline.getTime(); } else { return false; } }
Source:
START public Field notFound(Class<?> type, boolean isInstanceField) throws FieldNotFoundException { END throw new FieldNotFoundException(String.format( "No %s field of type \"%s\" could be found in the class hierarchy of %s.", isInstanceField ? "instance" : "static", expectedFieldType.getName(), type.getName())); } Hmm, what would you like to achieve keeping `void` in the interface?

Target:
public void notFound(Class<?> type, boolean isInstanceField) throws FieldNotFoundException { throw new FieldNotFoundException(String.format( "No %s field of type \"%s\" could be found in the class hierarchy of %s.", isInstanceField ? "instance" : "static", expectedFieldType.getName(), type.getName())); }
Source:
public PartialUpdate<T> del(String path) { Assert.hasText(path, "Path to remove must not be null or empty!"); START propertyUpdates.add(new PropertyUpdate(UpdateCommand.DEL, path)); END return new PartialUpdate<T>(this.id, this.target, this.value, this.refreshTtl, this.propertyUpdates); } `PartialUpdate` changes its own state and creates a new instance.

Target:
public PartialUpdate<T> del(String path) { Assert.hasText(path, "Path to remove must not be null or empty!"); PartialUpdate<T> update = new PartialUpdate<T>(this.id, this.target, this.value, this.refreshTtl, this.propertyUpdates); update.propertyUpdates.add(new PropertyUpdate(UpdateCommand.DEL, path)); return update; }
Source:
public List<Float> apply(Iterable<String> values) throws InvalidAttributeValueException { ImmutableList.Builder<Float> floats = ImmutableList.builder(); for (String value : values) { try { floats.add(Float.valueOf(value)); } catch (NumberFormatException nfe) { START throw new InvalidAttributeValueException(value); END } } return floats.build(); } Not to be a little female dog, but generally good style to include the cause in the exception you throw.

Target:
public List<Float> apply(Iterable<String> values) throws InvalidAttributeValueException { ImmutableList.Builder<Float> floats = ImmutableList.builder(); for (String value : values) { try { floats.add(Float.valueOf(value)); } catch (NumberFormatException e) { throw new InvalidAttributeValueException(value, e); } } return floats.build(); }
Source:
public void unlock(T id) { log.trace("{} trying to unlock {}", Thread.currentThread().getName(), id.toString()); synchronized (locked) { if (locked.remove(id)) { log.trace("{} unlocked {}", Thread.currentThread().getName(), id.toString()); START idsLocked.update(-1); END locked.notifyAll(); } } } `idsLocked` is a histogram that records how many Ids are locked at a time every time someones calls lock(). It's not a counter. This statement effectively means that someone tried to lock -1 ids.

Target:
public void unlock(T id) { log.trace("{} trying to unlock {}", Thread.currentThread().getName(), id.toString()); synchronized (locked) { if (locked.remove(id)) { log.trace("{} unlocked {}", Thread.currentThread().getName(), id.toString()); locked.notifyAll(); } } }
Source:
START protected void removeColumn(ColumnListMutation<String> mutation, String column) { END mutation.deleteColumn(column); } Don't you just love it when someone extracts an interface that can only ever be implemented by an Astyanax driver using Protobuf? :D

Target:
private void removeColumn(ColumnListMutation<String> mutation, String column) { mutation.deleteColumn(column); }
Source:
public void write(@Nonnull PriorityScoreReasons entity, @Nonnull FieldWriter writer, @Nonnull OutputContext ctxt) throws IOException { writer.writeList( "positive", "positive", START entity.getPositive() != null ? entity.getPositive() : null, END ctxt ); writer.writeList( "negative", "negative", entity.getNegative() != null ? entity.getNegative() : null, ctxt ); } This is pointless, it's equivalent to just passing `entity.getPositive()`.

Target:
public void write(@Nonnull PriorityScoreReasons entity, @Nonnull FieldWriter writer, @Nonnull OutputContext ctxt) throws IOException { writer.writeList( "positive", "positive", entity.getPositive(), ctxt ); writer.writeList( "negative", "negative", entity.getNegative(), ctxt ); }
Source:
public ListenableFuture<ResolvedEquivalents<E>> resolveIds(Iterable<Id> ids, ApplicationSources sources, Set<Annotation> activeAnnotations) { START if(!activeAnnotations.contains(Annotation.NON_MERGED)) { END ListenableFuture<ResolvedEquivalents<E>> unmerged = resolver.resolveIds(ids, sources.getEnabledReadSources(), activeAnnotations); return Futures.transform(unmerged, mergeUsing(sources)); } else { return resolver.resolveIdsWithoutEquivalence(ids, sources.getEnabledReadSources(), activeAnnotations); } } Best avoid negative conditions where it's reasonable. Positive assertions are a bit easier to reason about and that "!" can easily be missed. Here you can just flip the if.

Target:
public ListenableFuture<ResolvedEquivalents<E>> resolveIds(Iterable<Id> ids, ApplicationSources sources, Set<Annotation> activeAnnotations) { if(activeAnnotations.contains(Annotation.NON_MERGED)) { return resolver.resolveIdsWithoutEquivalence(ids, sources.getEnabledReadSources(), activeAnnotations); } else { ListenableFuture<ResolvedEquivalents<E>> unmerged = resolver.resolveIds(ids, sources.getEnabledReadSources(), activeAnnotations); return Futures.transform(unmerged, mergeUsing(sources)); } }
Source:
private boolean hasHigherPrecedence(Publisher currentPublisher, Publisher existingPublisher, Iterable<Publisher> publisherPrecedence) { for (Publisher publisher : publisherPrecedence) { if (publisher == existingPublisher) { return false; } if (publisher == currentPublisher) { return true; } } // This should never happen as the delegate uses the same publishers for the query START LOG.warn("Delegate content index returned publisher that was not asked for." END + " Requested publishers: {}", currentPublisher, publisherPrecedence); return false; } If this should really **never** **ever** happen, we should probably log it as an error, not warning.

Target:
private boolean hasHigherPrecedence(Publisher currentPublisher, Publisher existingPublisher, Iterable<Publisher> publisherPrecedence) { for (Publisher publisher : publisherPrecedence) { if (publisher == existingPublisher) { return false; } if (publisher == currentPublisher) { return true; } } // This should never happen as the delegate uses the same publishers for the query LOG.error("Delegate content index returned publisher that was not asked for." + " Requested publishers: {}", currentPublisher, publisherPrecedence); return false; }
Source:
START public CassandraSegmentStore(CassandraDataStaxClient cassandra, String keyspace, String tableName, END AliasIndex<Segment> aliasIndex, IdGenerator idGenerator, Equivalence<? super Segment> equivalence, MessageSender<ResourceUpdatedMessage> sender) { super(idGenerator, equivalence, sender, new SystemClock()); this.cassandra = checkNotNull(cassandra); this.aliasIndex = checkNotNull(aliasIndex); this.keyspace = checkNotNull(keyspace); this.tableName = checkNotNull(tableName); } this should probably be private

Target:
private CassandraSegmentStore(CassandraDataStaxClient cassandra, String keyspace, String tableName, AliasIndex<Segment> aliasIndex, IdGenerator idGenerator, Equivalence<? super Segment> equivalence, MessageSender<ResourceUpdatedMessage> sender) { super(idGenerator, equivalence, sender, new SystemClock()); this.cassandra = checkNotNull(cassandra); this.aliasIndex = checkNotNull(aliasIndex); this.keyspace = checkNotNull(keyspace); this.tableName = checkNotNull(tableName); }
Source:
public ModelAndView contextJSONLD(@RequestParam(value = "callback", required = false) String callback) { String jsonld = null; START try { jsonld = com.github.jsonldjava.utils.JsonUtils.toString(jsonldContext); } catch (IOException e) { LOG.error("Error in Json serialization", e); } END return JsonUtils.toJson(jsonld, callback); } removed

Target:
public ModelAndView contextJSONLD(@RequestParam(value = "callback", required = false) String callback) throws IOException { String jsonld = com.github.jsonldjava.utils.JsonUtils.toString(jsonldContext); return JsonUtils.toJson(jsonld, callback); }
Source:
public void turtleWriterTest() throws IOException { START InputStream rdfInput = TurtleRecordWriter.class.getClassLoader().getResourceAsStream(RDF_INPUT_TEST); END Model modelResult = ModelFactory.createDefaultModel().read(rdfInput, "", "RDF/XML"); OutputStream outputStream = new ByteArrayOutputStream(); TurtleRecordWriter writer= new TurtleRecordWriter(outputStream); writer.write(modelResult); //check if null Assert.assertNotNull(outputStream); outputStream.close(); } closed

Target:
public void turtleWriterTest() throws IOException { InputStream rdfInput = TurtleRecordWriter.class.getClassLoader().getResourceAsStream(RDF_INPUT_TEST); Model modelResult = ModelFactory.createDefaultModel().read(rdfInput, "", "RDF/XML"); OutputStream outputStream = new ByteArrayOutputStream(); TurtleRecordWriter writer= new TurtleRecordWriter(outputStream); writer.write(modelResult); //check if null Assert.assertNotNull(outputStream); //close the streams outputStream.close(); rdfInput.close(); }
Source:
START public long getSize() { END return size; } etc. for the rest

Target:
public long getSize() { return this.size; }
Source:
private String convertBoolean(final String value) { String result = value; if (result.equals("true")) { result = "Yes"; } START if (result.equals("false")) { END result = "No"; } return result; } I would recommend an `else if` here to avoid comparing against a string unnecessarily.

Target:
private String convertBoolean(final String value) { String result = value; if (result.equals("true")) { result = "Yes"; } else if (result.equals("false")) { result = "No"; } return result; }
Source:
public boolean isSuccess(CompletionStage<Void> future) { try { FunctionalTestUtils.await(future); return true; START } catch (Error e) { END return false; } } Why not ```catch Throwable``` ? I have strange gut feelings for Error

Target:
public boolean isSuccess(CompletionStage<Void> future) { try { FunctionalTestUtils.await(future); return true; } catch (Throwable e) { return false; } }
Source:
public void validate(GlobalConfiguration globalConfig) { Attribute<String> location = attributes.attribute(LOCATION); if (location.isNull() && !globalConfig.globalState().enabled()) { Log.CONFIG.storeLocationRequired(); START } END super.validate(globalConfig); } We can remove this as the error will always be thrown on startup via `PersistenceUtil#getLocation`.

Target:
public void validate(GlobalConfiguration globalConfig) { Attribute<String> location = attributes.attribute(LOCATION); if (location.isNull() && !globalConfig.globalState().enabled()) { throw Log.CONFIG.storeLocationRequired(); } super.validate(globalConfig); }
Source:
public AutoCloseable scheduleWithFixedDelay(Supplier<CompletionStage<?>> supplier, long initialDelay, long delay, TimeUnit unit) { ReschedulingTask task = new ReschedulingTask(supplier, delay, unit); START task.future = scheduler.schedule(task, initialDelay, unit); END return task; } synchronize? if `initialDelay` is zero, the scheduler may run the "task" before the `future`is set.

Target:
public AutoCloseable scheduleWithFixedDelay(Supplier<CompletionStage<?>> supplier, long initialDelay, long delay, TimeUnit unit) { ReschedulingTask task = new ReschedulingTask(supplier, delay, unit); synchronized (task) { task.future = scheduler.schedule(task, initialDelay, unit); } return task; }
Source:
private CompletionStage<Void> awaitQuiescence() { CompletionStage<Void> stage; synchronized (this) { stage = batchFuture; } if (stage == null) { return CompletableFutures.completedNull(); } if (trace) { log.tracef("Must wait until prior batch completes for %s", actual); } START return batchFuture.thenCompose(ignore -> awaitQuiescence()); END } ```suggestion return stage.thenCompose(ignore -> awaitQuiescence()); ```

Target:
private CompletionStage<Void> awaitQuiescence() { CompletionStage<Void> stage; synchronized (this) { stage = batchFuture; } if (stage == null) { return CompletableFutures.completedNull(); } if (trace) { log.tracef("Must wait until prior batch completes for %s", actual); } return stage.thenCompose(ignore -> awaitQuiescence()); }
Source:
public ForkedServer start() { boolean isServerStarted; ProcessBuilder pb = new ProcessBuilder(); pb.command(commands); try { process = pb.start(); isServerStarted = runWithTimeout(this::checkServerLog, START_PATTERN); if (!isServerStarted) { throw new IllegalStateException("The server couldn't start"); } } catch (Exception e) { log.error(e); } START log.info("SERVER STARTED!"); END return this; } No need for this.

Target:
public ForkedServer start() { boolean isServerStarted; ProcessBuilder pb = new ProcessBuilder(); pb.command(commands); try { process = pb.start(); isServerStarted = runWithTimeout(this::checkServerLog, START_PATTERN); if (!isServerStarted) { throw new IllegalStateException("The server couldn't start"); } } catch (Exception e) { log.error(e); } return this; }
Source:
AttributeChangeTracker(AttributeSet attributeSet) { attributeSet.attributes().forEach(a -> a.addListener((attr, oldVal) -> { if (this.isTracking) { String name = attr.name(); Object value = attr.get(); START changedAttributes.add(name.concat("=").concat(value == null ? "" : value.toString())); END } })); } Why calling concat here? I would worry this would prevent StringBuilder optimization for +'s.

Target:
AttributeChangeTracker(AttributeSet attributeSet) { attributeSet.attributes().forEach(a -> a.addListener((attr, oldVal) -> { if (this.isTracking) { String name = attr.name(); Object value = attr.get(); changedAttributes.add(name + "=" + (value == null ? "" : value.toString())); } })); }
Source:
public void listPatches(Path target, boolean verbose) { List<PatchInfo> installedPatches = getInstalledPatches(target); START if (installedPatches.size() == 0) { END out.println(MSG.patchNoPatchesInstalled()); } else { for (PatchInfo patchInfo : installedPatches) { out.println(MSG.patchInfo(patchInfo)); if (verbose) { patchInfo.getOperations().forEach(op -> out.println(" " + op)); } } } } ```suggestion if (installedPatches.isEmpty()) { ```

Target:
public void listPatches(Path target, boolean verbose) { List<PatchInfo> installedPatches = getInstalledPatches(target); if (installedPatches.isEmpty()) { out.println(MSG.patchNoPatchesInstalled()); } else { for (PatchInfo patchInfo : installedPatches) { out.println(MSG.patchInfo(patchInfo)); if (verbose) { patchInfo.getOperations().forEach(op -> out.println(" " + op)); } } } }
Source:
private boolean identifiedByName(Class<?> type) { START return Map.class.equals(type) || byte[].class.equals(type); END } I think this `Map.class.equals(type)` is a remnant from a previous implementation and can be removed?

Target:
private boolean identifiedByName(Class<?> type) { return byte[].class.equals(type); }
Source:
public void addItem(Object key, Object value, CompletableFuture<?> future) { // This is what HS5 currently does, but introduce chunking could be a good idea. future.whenComplete((result, exception) -> { if (exception != null) { notifier.notifyEntityIndexingFailure(value.getClass(), key, exception); } else { notifier.notifyDocumentsAdded(1); } }).thenCombine(lastFuture, (ignored1, ignored2) -> null); START } END You forgot to update `lastFuture`.

Target:
public void addItem(Object key, Object value, CompletableFuture<?> future) { // This is what HS5 currently does, but introduce chunking could be a good idea. lastFuture = future.whenComplete((result, exception) -> { if (exception != null) { notifier.notifyEntityIndexingFailure(value.getClass(), key, exception); } else { notifier.notifyDocumentsAdded(1); } }).thenCombine(lastFuture, (ignored1, ignored2) -> null); }
Source:
protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() START .addProperty(SearchConfig.DIRECTORY_TYPE, SearchConfig.HEAP); END return TestCacheManagerFactory.createCacheManager(builder); } Why does it need to be HEAP?

Target:
protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable(); return TestCacheManagerFactory.createCacheManager(builder); }
Source:
public <T, U> InternalRemoteCache<T, U> withDataFormat(DataFormat dataFormat) { InternalRemoteCache<T, U> newCache = delegate.withDataFormat(dataFormat); if (newCache != delegate) { return newDelegatingCache(newCache); } START return (InternalRemoteCache) this; END } Remove the warning from IDE ```suggestion //noinspection unchecked return (InternalRemoteCache<T, U>) this; ```

Target:
public <T, U> InternalRemoteCache<T, U> withDataFormat(DataFormat dataFormat) { InternalRemoteCache<T, U> newCache = delegate.withDataFormat(dataFormat); if (newCache != delegate) { return newDelegatingCache(newCache); } //noinspection unchecked return (InternalRemoteCache<T, U>) this; }
Source:
public static <K, V, C> Function<CacheEntry<K, V>, CacheEntry<K, C>> converterToFunction(KeyValueFilterConverter<? super K, ? super V, C> filterConverter) { START return new FilterConverterAsCacheEntryFunction<K, V, C>(filterConverter); END } IntelliJ says the type parameters are not needed

Target:
public static <K, V, C> Function<CacheEntry<K, V>, CacheEntry<K, C>> converterToFunction(KeyValueFilterConverter<? super K, ? super V, C> filterConverter) { return new FilterConverterAsCacheEntryFunction<>(filterConverter); }
Source:
START public boolean isConversionSupported(MediaType mediaType) { END if (encoderRegistry == null) return false; return encoderRegistry.isConversionSupported(storageMediaType, mediaType); } I just updated https://github.com/infinispan/infinispan/pull/8196

Target:
public boolean isConversionSupported(MediaType mediaType) { return storageMediaType == null || encoderRegistry.isConversionSupported(storageMediaType, mediaType); }
Source:
private CacheEventFilter<Object, String> filter(Object keyToFilter) { return (Serializable & CacheEventFilter<Object, String>) (k, oldValue, oldMetadata, newValue, newMetadata, eventType) -> { START boolean retVal = Objects.equals(k, keyToFilter); END return retVal; }; } Can make this one line and remove brackets now.

Target:
private CacheEventFilter<Object, String> filter(Object keyToFilter) { return (Serializable & CacheEventFilter<Object, String>) (k, oldValue, oldMetadata, newValue, newMetadata, eventType) -> Objects.equals(k, keyToFilter); }
Source:
public void testSingleServer() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.clientIntelligence(ClientIntelligence.BASIC); RemoteCache<String, String> cache = SERVER_TEST.hotrod().withClientConfiguration(builder).withCacheMode(CacheMode.DIST_SYNC).create(); START cache.put("k1", "v1"); END assertEquals(1, cache.size()); assertEquals("v1", cache.get("k1")); } Wrong indent, and the previous line should be wrapped

Target:
public void testSingleServer() { RemoteCache<String, String> cache = SERVER_TEST .hotrod() .withCacheMode(CacheMode.DIST_SYNC).create(); cache.put("k1", "v1"); assertEquals(1, cache.size()); assertEquals("v1", cache.get("k1")); }
Source:
Object extractValue(DocumentExtractor extractor, int docIndex) { Object[] projection; try { projection = extractor.extract(docIndex).getProjection(); } catch (IOException e) { throw new SearchException("Error while extracting projection", e); } if (projection == null) { Object key = extractKey(extractor, docIndex); START return cache.get(fromStorage(key)); END } return projection; } Here too, if the cache injected in components has request media type == storage media type, then the conversion isn't necessary. Edit: You would still have to convert the value to the request media type, but I would rather make that conversion explicit here instead of converting the key back and forth.

Target:
Object extractValue(DocumentExtractor extractor, int docIndex) { Object[] projection; try { projection = extractor.extract(docIndex).getProjection(); } catch (IOException e) { throw new SearchException("Error while extracting projection", e); } if (projection == null) { Object key = extractKey(extractor, docIndex); return cache.get(key); } return projection; }
Source:
public RepeatableReadEntry(Object key, Object value, Metadata metadata) { super(key, value, metadata); START this.oldMetadata = metadata; END } I think you need to move the `oldMetadata` to `ReadCommittedEntry`

Target:
public RepeatableReadEntry(Object key, Object value, Metadata metadata) { super(key, value, metadata); }
Source:
public void serialize(Appender appender, JsonGenerator json, SerializerProvider serializerProvider) throws IOException { json.writeStartObject(); json.writeStringField("name", appender.getName()); START Layout<? extends Serializable> layout = appender.getLayout(); END json.writeEndObject(); } layout isn't used.

Target:
public void serialize(Appender appender, JsonGenerator json, SerializerProvider serializerProvider) throws IOException { json.writeStartObject(); json.writeStringField("name", appender.getName()); json.writeEndObject(); }
Source:
public void segmentsFinished(byte[] finishedSegments) { START if (trackSegments) { END if (finishedSegments != null) { BitSet bitSet = BitSet.valueOf(finishedSegments); if (trace) log.tracef("Removing completed segments %s", bitSet); bitSet.stream().forEach(seg -> keysPerSegment.set(seg, null)); } } } nitpick: `if (trackeSegments && finishedSegments != null)`

Target:
public void segmentsFinished(byte[] finishedSegments) { if (trackSegments && finishedSegments != null) { BitSet bitSet = BitSet.valueOf(finishedSegments); if (trace) log.tracef("Removing completed segments %s", bitSet); bitSet.stream().forEach(seg -> keysPerSegment.set(seg, null)); } }
Source:
public IndexingConfigurationBuilder index(Index index) { START if (index != Index.NONE) enabled(true); END attributes.attribute(INDEX).set(index); return this; } The conditional thing seems wrong. This should probably be just ```enabled(index !=null && index != Index.NON);```

Target:
public IndexingConfigurationBuilder index(Index index) { enabled(index != null && index != Index.NONE); attributes.attribute(INDEX).set(index); return this; }
Source:
START public TaskParameter(String key, String value) { END this.key = key; this.value = value; } Class and constructor can be package-private as only used internally.

Target:
TaskParameter(String key, String value) { this.key = key; this.value = value; }
Source:
public CompletableFuture<Object> invokeAsync(InvocationContext ctx, VisitableCommand command) { try { START command.init(componentRegistry); END Object result = firstInterceptor.visitCommand(ctx, command); if (result instanceof InvocationStage) { return ((InvocationStage) result).toCompletableFuture(); } else { // Don't allocate future if result was already null if (result == null) { return CompletableFutures.completedNull(); } return CompletableFuture.completedFuture(result); } } catch (Throwable t) { return CompletableFutures.completedExceptionFuture(t); } } I don't think this is needed on the originator: `keyDataConversion` and `valueDataConversion` are not private to the command, they're already wired, and even if `wireDependencies` is idempotent, it's not that cheap. `SingleRpcCommand` and `PrepareCommand` already init the sub-commands on the target nodes, you just need to add it in `BackupWriteCommand`.

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 { // Don't allocate future if result was already null if (result == null) { return CompletableFutures.completedNull(); } return CompletableFuture.completedFuture(result); } } catch (Throwable t) { return CompletableFutures.completedExceptionFuture(t); } }
Source:
public boolean hasZeroLockAcquisition() { if (modifications == null || modifications.length == 0) { return false; } boolean hasZeroLock = true; for (WriteCommand wc : modifications) { // If even a single command doesn't have the zero lock acquisition timeout flag, we can't use a zero timeout if (!wc.hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT)) { START hasZeroLock = false; END break; } } return hasZeroLock; } Could `return false` and avoid the variable.

Target:
public boolean hasZeroLockAcquisition() { if (modifications == null || modifications.length == 0) { return false; } for (WriteCommand wc : modifications) { // If even a single command doesn't have the zero lock acquisition timeout flag, we can't use a zero timeout if (!wc.hasAnyFlag(FlagBitSets.ZERO_LOCK_ACQUISITION_TIMEOUT)) { return false; } } return true; }
Source:
AdvancedCache<K, V> cacheToUse(boolean isWrite) { // For non writes we don't have any lock wait time. This is to prevent deadlocks with a concurrent write and // also so that multiple gets, only one will win. // Pessimistic caches will already hold the lock for the read value and thus we have to skip locking // Optimistic will not hold the lock at this point and thus we always have to lock the entry START return isWrite ? optimisticTransaction ? cache : cache.withFlags(Flag.SKIP_LOCKING) : cache.withFlags(Flag.ZERO_LOCK_ACQUISITION_TIMEOUT); END } Some parentheses to improve readability please

Target:
AdvancedCache<K, V> cacheToUse(boolean isWrite) { // For non writes we don't have any lock wait time. This is to prevent deadlocks with a concurrent write and // also so that with concurrent gets, only one will win. // Pessimistic caches will already hold the lock for the read value and thus we have to skip locking // Optimistic will not hold the lock at this point and thus we always have to lock the entry return isWrite ? (optimisticTransaction ? cache : cache.withFlags(Flag.SKIP_LOCKING)) : cache.withFlags(Flag.ZERO_LOCK_ACQUISITION_TIMEOUT); }
Source:
final CompletableFuture<Void> removeLifespanExpired(K key, V value, Long lifespan, long explicitFlags) { START long flagBitSet = explicitFlags | FlagBitSets.SKIP_CACHE_LOAD | FlagBitSets.SKIP_SHARED_CACHE_STORE | FlagBitSets.SKIP_XSITE_BACKUP; END RemoveExpiredCommand command = commandsFactory.buildRemoveExpiredCommand(key, value, keyPartitioner.getSegment(key), lifespan, flagBitSet); // Remove expired returns a boolean - just ignore it, the caller just needs to know that the expired // entry is removed when this completes CompletableFuture<Boolean> completableFuture = performRemoveExpiredCommand(command); return completableFuture.thenApply(b -> null); } I don't think we can do this here. We need to set the flag on the cache in the reaper. Otherwise a get which removes the expired entry won't remove the entry from the shared store possibly.

Target:
final CompletableFuture<Void> removeLifespanExpired(K key, V value, Long lifespan, long explicitFlags) { RemoveExpiredCommand command = commandsFactory.buildRemoveExpiredCommand(key, value, keyPartitioner.getSegment(key), lifespan, explicitFlags | FlagBitSets.SKIP_CACHE_LOAD | FlagBitSets.SKIP_XSITE_BACKUP); // Remove expired returns a boolean - just ignore it, the caller just needs to know that the expired // entry is removed when this completes CompletableFuture<Boolean> completableFuture = performRemoveExpiredCommand(command); return completableFuture.thenApply(b -> null); }
Source:
public CommandResult exec(ContextAwareCommandInvocation invocation) { if (help) { invocation.println(invocation.getHelpInfo()); } CommandInputLine cmd = new CommandInputLine(Task.CMD) .arg(TYPE, Task.Exec.CMD) .arg(NAME, taskName) START .arg(PARAMETERS, parameters != null ? parameters : Collections.emptyMap()); END return invocation.execute(cmd); } why not init the parameters to emptyMap ?

Target:
public CommandResult exec(ContextAwareCommandInvocation invocation) { if (help) { invocation.println(invocation.getHelpInfo()); } CommandInputLine cmd = new CommandInputLine(Task.CMD) .arg(TYPE, Task.Exec.CMD) .arg(NAME, taskName) .arg(PARAMETERS, parameters == null ? Collections.emptyMap() : parameters); return invocation.execute(cmd); }
Source:
public String describe() throws IOException { START return NAME;//TODO END } //TODO ?

Target:
public String describe() { return NAME; }
Source:
public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalConfiguration) { BasicComponentRegistry bcr = gcr.getComponent(BasicComponentRegistry.class); Interpreter interpreter = new Interpreter(); START bcr.registerComponent(Interpreter.class, interpreter, true); END if (globalConfiguration.statistics()) { try { CacheManagerJmxRegistration jmxRegistration = bcr.getComponent(CacheManagerJmxRegistration.class).running(); jmxRegistration.registerMBean(interpreter); } catch (Exception e) { log.jmxRegistrationFailed(); } } } -1 since the interpreter is only used with JMX now.

Target:
public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalConfiguration) { if (globalConfiguration.statistics()) { BasicComponentRegistry bcr = gcr.getComponent(BasicComponentRegistry.class); Interpreter interpreter = new Interpreter(); bcr.registerComponent(Interpreter.class, interpreter, true); try { CacheManagerJmxRegistration jmxRegistration = bcr.getComponent(CacheManagerJmxRegistration.class).running(); jmxRegistration.registerMBean(interpreter); } catch (Exception e) { throw log.jmxRegistrationFailed(e); } } }
Source:
START public void verifyTopology(LocalizedCacheTopology localizedCacheTopology) { END for (PrimitiveIterator.OfInt segmentIterator = segments.iterator(); segmentIterator.hasNext(); ) { int segment = segmentIterator.nextInt(); if (!localizedCacheTopology.isSegmentReadOwner(segment)) { if (trace) { log.tracef("Listener %s lost segment %d before invocation", this, segment); } segmentIterator.remove(); } } } protected or package-private

Target:
void verifyTopology(LocalizedCacheTopology localizedCacheTopology) { for (PrimitiveIterator.OfInt segmentIterator = segments.iterator(); segmentIterator.hasNext(); ) { int segment = segmentIterator.nextInt(); if (!localizedCacheTopology.isSegmentReadOwner(segment)) { if (trace) { log.tracef("Listener %s lost segment %d before invocation", this, segment); } segmentIterator.remove(); } } }
Source:
START public void clearTempDir() { END Util.recursiveFileRemove(tmpDirectory); } Need `@AfterClass(alwaysRun = true)` as well to run after failures Edit: Also `if (tmpDirectory != null)`

Target:
public void clearTempDir() { if (tmpDirectory != null) { Util.recursiveFileRemove(tmpDirectory); } }
Source:
protected void adaptLONConfiguration(BackupConfigurationBuilder builder) { START builder.stateTransfer().chunkSize(2).timeout(2000).maxRetries(2); END } Ouch, default MAX_RETRIES is 30??? To me even 2 is excessive in a test :)

Target:
protected void adaptLONConfiguration(BackupConfigurationBuilder builder) { builder.stateTransfer().chunkSize(2).timeout(2000).maxRetries(1); }
Source:
public void validate() { if (connectionFactory != null) { connectionFactory.validate(); } // TODO: I don't think this is quite correct... START if (attributes.attribute(MANAGE_CONNECTION_FACTORY).get() && (connectionFactory == null || connectionFactory.needsManaging())) { END table.validate(); } super.validate(); } Can't we do this without the need for the `needsManaging` interface. The following should be sufficient: ```java if (!attributes.attribute(MANAGE_CONNECTION_FACTORY).get()) table.validate() ``` If we add `builder.manageConnectionFactory(false);` to the `ManagedConnectionFactoryConfigurationBuilder` constructor.

Target:
public void validate() { table.validate(); super.validate(); }
Source:
public CommandResult exec(ContextAwareCommandInvocation invocation) { if (help) { invocation.println(invocation.getHelpInfo()); } CommandInputLine cmd = new CommandInputLine(Shutdown.CMD) .arg(TYPE, Shutdown.Cluster.CMD); START return invocation.execute(Collections.singletonList(cmd)); END } why do we need a `Collections.singletonList(cmd)` here?

Target:
public CommandResult exec(ContextAwareCommandInvocation invocation) { if (help) { invocation.println(invocation.getHelpInfo()); } CommandInputLine cmd = new CommandInputLine(Shutdown.CMD) .arg(TYPE, Shutdown.Cluster.CMD); return invocation.execute(cmd); }
Source:
public Collection<String> getAvailableServers(String container) throws IOException { START List<String> members = (List<String>) parseBody(fetch(() -> client.cacheManager(container).info()), Map.class).get("cluster_members"); END return members; } remove `members`?

Target:
public Collection<String> getAvailableServers(String container) throws IOException { return (List<String>) parseBody(fetch(() -> client.cacheManager(container).info()), Map.class).get("cluster_members"); }
Source:
START public HashSet<V> toSet() { END return new HashSet<>(values); } Can we have this return `Set` :)

Target:
public Set<V> toSet() { return new HashSet<>(values); }
Source:
private void update(MarshallerType type, Consumer<MarshallerContext> consumer) { if (type == GLOBAL) { synchronized (global) { consumer.accept(global); } START return; END } synchronized (persistence) { consumer.accept(persistence); } } I would personally have preferred an else block, but I am fine with how you have it.

Target:
private void update(MarshallerType type, Consumer<MarshallerContext> consumer) { if (type == GLOBAL) { synchronized (global) { consumer.accept(global); } } else { synchronized (persistence) { consumer.accept(persistence); } } }
Source:
public CommandInputLine option(String name, Integer value) { if (value != null) { START this.options.put(name, Integer.valueOf(value)); END } return this; } Guessing you wanted the argument to be `int`? If not then the `valueOf` is unneeded.

Target:
public CommandInputLine option(String name, Integer value) { if (value != null) { this.options.put(name, value); } return this; }
Source:
public SpringRemoteCacheManagerFactoryBean springCacheManager() { SpringRemoteCacheManagerFactoryBean factoryBean = new SpringRemoteCacheManagerFactoryBean(); factoryBean.setServerList(Arrays.asList(new InetSocketAddress("localhost", SERVER_PORT))); START factoryBean.setMarshaller(JavaSerializationMarshaller.class.getName()); END factoryBean.setClassWhiteList(AbstractRemoteCacheManagerFactory.SPRING_JAVA_SERIAL_WHITELIST + ",java.util.*"); return factoryBean; } this shouldn't be necessary at this point, am I wrong ?

Target:
public SpringRemoteCacheManagerFactoryBean springCacheManager() { SpringRemoteCacheManagerFactoryBean factoryBean = new SpringRemoteCacheManagerFactoryBean(); factoryBean.setServerList(Arrays.asList(new InetSocketAddress("localhost", SERVER_PORT))); factoryBean.setClassWhiteList(AbstractRemoteCacheManagerFactory.SPRING_JAVA_SERIAL_WHITELIST + ",java.util.*"); return factoryBean; }
Source:
protected String initDomain() { if (!globalJmxRegistration.isJMXEnabled()) { if (globalJmxRegistration.mBeanServer == null) { globalJmxRegistration.mBeanServer = mBeanServer; } globalJmxRegistration.initJMX(); } return globalJmxRegistration.jmxDomain; START } END Why do we set the global jmx `mBeanServer` to the cache's mBeanServer if JMX is disabled globally?

Target:
protected String initDomain() { return globalJmxRegistration.jmxDomain; }
Source:
START protected void assertEventuallyStateTransferNotRunning() { END eventually(() -> adminOperations().getRunningStateTransfer().isEmpty(), 30, TimeUnit.SECONDS); } unneeded change

Target:
void assertEventuallyStateTransferNotRunning() { eventually(() -> adminOperations().getRunningStateTransfer().isEmpty(), 30, TimeUnit.SECONDS); }
Source:
public ProtostreamTranscoder(SerializationContext ctx, ClassLoader classLoader) { super(APPLICATION_PROTOSTREAM, APPLICATION_OCTET_STREAM, TEXT_PLAIN, APPLICATION_OBJECT, APPLICATION_JSON, APPLICATION_UNKNOWN); this.ctx = ctx; this.marshaller = new ProtoStreamMarshaller(ctx); this.classLoader = classLoader; START } END `ProtoStreamMarshaller` is also using the `SerializationContext`. Shouldn't be updated?

Target:
public ProtostreamTranscoder(SerializationContext ctx, ClassLoader classLoader) { super(APPLICATION_PROTOSTREAM, APPLICATION_OCTET_STREAM, TEXT_PLAIN, APPLICATION_OBJECT, APPLICATION_JSON, APPLICATION_UNKNOWN); this.ctx = ctx; this.classLoader = classLoader; }
Source:
public GenericJBossMarshaller(ClassLoader classLoader, ClassWhiteList classWhiteList) { super(); START this.classLoader = classLoader == null ? getClass().getClassLoader() : classLoader; END baseCfg.setClassResolver(classWhiteList == null ? new DefaultContextClassResolver(classLoader) : new CheckedClassResolver(classWhiteList, classLoader) ); } Not doing ```getClass().getClassLoader()``` and just leaving it null would default to TCCL. Not sure which one is best.

Target:
public GenericJBossMarshaller(ClassLoader classLoader, ClassWhiteList classWhiteList) { super(); if (classLoader == null) { classLoader = getClass().getClassLoader(); } baseCfg.setClassResolver(classWhiteList == null ? new DefaultContextClassResolver(classLoader) : new CheckedClassResolver(classWhiteList, classLoader) ); }
Source:
public ModulusOffsetCalculator(int numBlocks) { int blocksMinusOne = numBlocks - 1; // We need a positive offset count // And it has to be a power of 2 START if (numBlocks <= 0 && (numBlocks & blocksMinusOne) == 0) { END throw new IllegalArgumentException("maxOffset " + numBlocks + " must be greater than 0 and a power of 2"); } this.blocksMinusOne = blocksMinusOne; } ```suggestion if (numBlocks <= 0 || (numBlocks & blocksMinusOne) != 0) { ```

Target:
public ModulusOffsetCalculator(int numBlocks) { int blocksMinusOne = numBlocks - 1; // We need a positive offset count // And it has to be a power of 2 if (numBlocks <= 0 || (numBlocks & blocksMinusOne) != 0) { throw new IllegalArgumentException("maxOffset " + numBlocks + " must be greater than 0 and a power of 2"); } this.blocksMinusOne = blocksMinusOne; }
Source:
void free(long address) { if (trace) { START Long prev = allocatedBlocks.remove(address); END if (prev == null) { throw new IllegalArgumentException(); } } UNSAFE.freeMemory(address); } Oops, good catch!

Target:
void free(long address) { Long prev = allocatedBlocks.remove(address); if (trace) { if (prev == null) { throw new IllegalArgumentException(); } } UNSAFE.freeMemory(address); }
Source:
public synchronized void updateOnCommunicationFailure(long sendTimeMillis) { if (!recordingOfflineStatus) { if (trace) { START log.trace("Start recording failures"); END } recordingOfflineStatus = true; firstFailureTime = sendTimeMillis; } failureCount++; if (trace) { log.tracef("Failures count: %s", failureCount); } } Is this really needed?

Target:
public synchronized void updateOnCommunicationFailure(long sendTimeMillis) { if (!recordingOfflineStatus) { recordingOfflineStatus = true; firstFailureTime = sendTimeMillis; } failureCount++; }
Source:
public CompletionStage<?> applyState(Address sender, int topologyId, boolean pushTransfer, Collection<StateChunk> stateChunks) { expectLatch.countDown(); try { assertTrue(blockLatch.await(10, TimeUnit.SECONDS)); } catch (InterruptedException e) { throw new RuntimeException(e); } super.applyState(sender, topologyId, pushTransfer, stateChunks); START return null; END } Should this return the value of the previous line?

Target:
public CompletionStage<?> applyState(Address sender, int topologyId, boolean pushTransfer, Collection<StateChunk> stateChunks) { expectLatch.countDown(); try { assertTrue(blockLatch.await(10, TimeUnit.SECONDS)); } catch (InterruptedException e) { throw new RuntimeException(e); } return super.applyState(sender, topologyId, pushTransfer, stateChunks); }
Source:
public CompletionStage<?> applyState(Address sender, int topologyId, boolean pushTransfer, Collection<StateChunk> stateChunks) { delegate.applyState(sender, topologyId, pushTransfer, stateChunks); START return null; END } This should return the previous line as well.

Target:
public CompletionStage<?> applyState(Address sender, int topologyId, boolean pushTransfer, Collection<StateChunk> stateChunks) { return delegate.applyState(sender, topologyId, pushTransfer, stateChunks); }
Source:
static void addInternalClassesToWhiteList(ClassWhiteList list) { // Infinispan Enums with no Externalizer list.addClasses( BackupSender.BringSiteOnlineResponse.class, BackupSender.TakeSiteOfflineResponse.class, CacheMode.class, XSiteAdminCommand.AdminOperation.class, XSiteAdminCommand.Status.class ); START list.addClasses(Enum.class, Number.class, Object.class, Object[].class, SerializedLambda.class); END } This would also allow removing Enum from this list. Object class isn't Serializable, why is this here?

Target:
static void addInternalClassesToWhiteList(ClassWhiteList list) { list.addClasses(Number.class, Object.class, Object[].class, SerializedLambda.class); }
Source:
public void scheduleTimeout(Channel channel) { assert timeoutFuture == null; START this.timeoutFuture = channel.eventLoop().schedule(new TimeoutRunnable(channel), channelFactory.socketTimeout(), TimeUnit.MILLISECONDS); END } Meh, that means a new allocation in each operation :-/ I wonder how much mess would be storing the channel directly in the `HotRodOperation`.

Target:
public void scheduleTimeout(Channel channel) { assert timeoutFuture == null; this.channel = channel; this.timeoutFuture = channel.eventLoop().schedule(this, channelFactory.socketTimeout(), TimeUnit.MILLISECONDS); }
Source:
public void handleCreatedEvent(ClientCacheEntryCreatedEvent e) { START createdEvents.add(e); END System.out.println("Created " + e); } You'd probably rather use logging here?

Target:
public void handleCreatedEvent(ClientCacheEntryCreatedEvent e) { createdEvents.add(e); }
Source:
START MemcachedMetadata(long flags, long lifespan, EntryVersion version) { END super(lifespan, version); this.flags = flags; } This can be private as it was before.

Target:
private MemcachedMetadata(long flags, long lifespan, EntryVersion version) { super(lifespan, version); this.flags = flags; }
Source:
public String toString() { return "EmbeddedMaxIdleExpirableMetadata{" + START "version=" + version() + END ", maxIdle=" + maxIdle + '}'; } ```version``` is protected. I don't think we need to access it via its accessor

Target:
public String toString() { return "EmbeddedMaxIdleExpirableMetadata{" + "version=" + version + ", maxIdle=" + maxIdle + '}'; }
Source:
public <K, V> CompletionStage<KeyValueStore<K, V>> getKeyValueStore(String name, KeyValueStoreConfig config) { return CompletableFuture.supplyAsync(() -> { addProtobufSchema(config); RemoteCache<K, V> cache = cacheManager.getCache(name, false); RemoteCache<K, V> cacheWithReturnValues = cacheManager.getCache(name, true); START return new KeyValueStoreImpl(cache, cacheWithReturnValues); END }, asyncExecutorService); } `<>` missing

Target:
public <K, V> CompletionStage<KeyValueStore<K, V>> getKeyValueStore(String name, KeyValueStoreConfig config) { return CompletableFuture.supplyAsync(() -> { addProtobufSchema(config); RemoteCache<K, V> cache = cacheManager.getCache(name, false); RemoteCache<K, V> cacheWithReturnValues = cacheManager.getCache(name, true); return new KeyValueStoreImpl<>(cache, cacheWithReturnValues); }, asyncExecutorService); }
Source:
public ClientKeyValueStoreListener(EntryStatus[] types) { List<EntryStatus> eventTypes = Arrays.asList(types); START listenCreated = eventTypes.contains(EntryStatus.CREATED) ? true : false; END listenUpdated = eventTypes.contains(EntryStatus.UPDATED) ? true : false; listenDeleted = eventTypes.contains(EntryStatus.DELETED) ? true : false; } `eventTypes.contains()` is enough xD

Target:
private ClientKeyValueStoreListener(EntryStatus[] types) { List<EntryStatus> eventTypes = Arrays.asList(types); listenCreated = eventTypes.contains(EntryStatus.CREATED); listenUpdated = eventTypes.contains(EntryStatus.UPDATED); listenDeleted = eventTypes.contains(EntryStatus.DELETED); }
Source:
public void subscribe(Subscriber<? super KeyValueEntry<K, V>> subscriber) { subscribers.add(subscriber); createContinuousQueryFlowable(); flowable.subscribe(subscriber); START flowable.doOnError(e -> { END log.error(e); continuousQuery.removeContinuousQueryListener(continuousQueryListener); }).doOnCancel(() -> continuousQuery.removeContinuousQueryListener(continuousQueryListener)); } do you need to add the error and cancel handles every time? can it be done when you create the `flowable`?

Target:
public void subscribe(Subscriber<? super KeyValueEntry<K, V>> subscriber) { createContinuousQueryFlowable(); flowable.subscribe(subscriber); }
Source:
START public void setBytes(byte[] bytes) { END this.bytes = bytes; this.hash = Arrays.hashCode(bytes); } I'd really really like `ByteString` objects to be immutable, because we use them in a lot of places.

Target:
void setBytes(byte[] bytes) { this.bytes = bytes; this.hash = Arrays.hashCode(bytes); }
Source:
Set<String> getFileNames() { readLock.lock(); try { return filenames; } finally { START readLock.unlock(); END } } The caller is going to use the collection outside the lock and the field is final, so the lock doesn't do anything. I think this needs a custom MessageMarshaller.

Target:
Set<String> getFileNames() { readLock.lock(); try { return new HashSet<>(filenames); } finally { readLock.unlock(); } }
Source:
public void startUp() { cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()); assertEquals(cacheManager.getCache().size(), 0); START TestingUtil.registerTranscoders(cacheManager, new ProtostreamBinaryTranscoder()); END hotRodServer = HotRodTestingUtil.startHotRodServer(cacheManager, 19711); } I'm surprised the server doesn't already do this.

Target:
public void startUp() { cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()); assertEquals(cacheManager.getCache().size(), 0); hotRodServer = HotRodTestingUtil.startHotRodServer(cacheManager, 19711); }
Source:
public void testIterationStateReaperOnClosedConnections() throws InterruptedException { IterationManager iterationManager = server().getIterationManager(); for (int i = 0; i < 10; i++) { hotRodClient.iteratorStart(null, null, null, 10, false); START } END hotRodClient.stop().await(); assertEquals(0, iterationManager.activeIterations()); } Thinking we should verify that there are actually 10 active iterations before stopping the client. Same with the reaper timeout below.

Target:
public void testIterationStateReaperOnClosedConnections() throws InterruptedException { IterationManager iterationManager = server().getIterationManager(); for (int i = 0; i < 10; i++) { hotRodClient.iteratorStart(null, null, null, 10, false); } assertEquals(10, iterationManager.activeIterations()); hotRodClient.stop().await(); assertEquals(0, iterationManager.activeIterations()); }
Source:
default Publisher<MarshalledEntry<K, V>> publishEntries(IntSet segments, Predicate<? super K> filter, boolean fetchValue, boolean fetchMetadata) { START return null; END } Doesn't seem right

Target:
default Publisher<MarshalledEntry<K, V>> publishEntries(IntSet segments, Predicate<? super K> filter, boolean fetchValue, boolean fetchMetadata) { return publishEntries(filter, fetchValue, fetchMetadata); }
Source:
public SuccessfulResponse addResponse(Address sender, Response response) { if (response.isSuccessful()) { return (SuccessfulResponse) response; } if (response instanceof ExceptionResponse) { throw ResponseCollectors.wrapRemoteException(sender, ((ExceptionResponse) response).getException()); } if (response instanceof UnsureResponse) { START hasUnsureResponse = true; END return null; } else if (response instanceof CacheNotFoundResponse) { hasSuspectResponse = true; return null; } throw ResponseCollectors.unexpectedResponse(response); } Looks like this field is never read.

Target:
public SuccessfulResponse addResponse(Address sender, Response response) { if (response.isSuccessful()) { return (SuccessfulResponse) response; } if (response instanceof ExceptionResponse) { throw ResponseCollectors.wrapRemoteException(sender, ((ExceptionResponse) response).getException()); } if (response instanceof UnsureResponse) { return null; } else if (response instanceof CacheNotFoundResponse) { hasSuspectResponse = true; return null; } throw ResponseCollectors.unexpectedResponse(response); }