auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
default Long getGlobalAddress() { if (getMetadataMap() == null) { START return Address.NON_ADDRESS; END } return Optional.ofNullable((Long) getMetadataMap() .get(LogUnitMetadataType.GLOBAL_ADDRESS)).orElse(Address.NON_ADDRESS); } I don't think you need this, Its either empyt, or it doesn't have the key.

Target:
default Long getGlobalAddress() { return Optional.ofNullable((Long) getMetadataMap() .get(LogUnitMetadataType.GLOBAL_ADDRESS)).orElse(Address.NON_ADDRESS); }
Source:
protected List<ILogData> getNextEntries(T context, long maxGlobal, Function<ILogData, Boolean> contextCheckFn) { final List<ILogData> dataList = new ArrayList<>(); ILogData thisData; START while ((thisData = streamReadWithCheck(()->getNextEntry(context, maxGlobal), maxGlobal)) != null) { END // Add this read to the list of reads to return. dataList.add(thisData); // Update the pointer, because the underlying implementation // will expect it to be updated when we call getNextEntry() again. updatePointer(thisData); // If this entry changes the context, don't continue reading. if (contextCheckFn.apply(thisData)) { break; } } return dataList; } This getNextEntries is the super class impl, it has a overridden impl. You need to change that.

Target:
protected List<ILogData> getNextEntries(T context, long maxGlobal, Function<ILogData, Boolean> contextCheckFn) { final List<ILogData> dataList = new ArrayList<>(); ILogData thisData; while ((thisData = getNextEntry(context, maxGlobal)) != null) { // Add this read to the list of reads to return. dataList.add(thisData); // Update the pointer, because the underlying implementation // will expect it to be updated when we call getNextEntry() again. updatePointer(thisData); // If this entry changes the context, don't continue reading. if (contextCheckFn.apply(thisData)) { break; } } return dataList; }
Source:
public synchronized ILogData current() { final QueuedStreamContext context = getCurrentContext(); if (Address.nonAddress(context.getGlobalPointer())) { return null; } // The ILogData returned by current() would be used for rollback. START return read(context.getGlobalPointer()); END } Why you are not checking compaction mark here?

Target:
public synchronized ILogData current() { final QueuedStreamContext context = getCurrentContext(); if (Address.nonAddress(context.getGlobalPointer())) { return null; } // The ILogData returned by current() would be used for rollback. return read(context.getGlobalPointer(), context.getGlobalPointer()); }
Source:
public void gcUnsafe() { while (garbageSendingDeque.size() < SENDING_QUEUE_CAPACITY) { List<SMRGarbageEntry> garbageEntries = new ArrayList<>(); START int drainedNum = garbageReceivingQueue.drainTo(garbageEntries, BATCH_SIZE); END GarbageBatch garbageBatch = new GarbageBatch(compressGarbage(garbageEntries)); garbageSendingDeque.offer(garbageBatch); if (drainedNum < BATCH_SIZE) { break; } } log.debug("GarbageInformer: Drains sending queue"); sendGarbage(); } Check drainedNum == 0 right after this line? Otherwise your batch could be zero.

Target:
public void gcUnsafe() { while (garbageSendingDeque.size() < SENDING_QUEUE_CAPACITY) { List<SMRGarbageEntry> garbageEntries = new ArrayList<>(); int drainedNum = garbageReceivingQueue.drainTo(garbageEntries, BATCH_SIZE); // checks drainNum to prevent empty garbage batch if (drainedNum == 0) { break; } GarbageBatch garbageBatch = new GarbageBatch(compressGarbage(garbageEntries)); garbageSendingDeque.offer(garbageBatch); if (drainedNum < BATCH_SIZE) { break; } } log.debug("GarbageInformer: Drains sending queue"); sendGarbage(); }
Source:
protected List<Object> identifyRemoveGarbage(Object locator, K key) { List<Object> garbage = new ArrayList<>(); // TODO(Xin): Distinguish put and remove in the future START garbage.addAll(locatorStore.addUnsafe(key, (SMRRecordLocator) locator)); END return garbage; } Same here, you can use `List<Object> garbage = new ArrayList<>(locatorStore.addUnsafe(key, (SMRRecordLocator) locator));`

Target:
protected List<Object> identifyRemoveGarbage(Object locator, K key) { // TODO(Xin): Distinguish put and remove in the future return new ArrayList<>(locatorStore.addUnsafe(key, (SMRRecordLocator) locator)); }
Source:
protected List<Object> identifyClearGarbage(Object locator) { List<Object> garbage = new ArrayList<>(); START garbage.addAll(locatorStore.clearUnsafe()); END return garbage; } Make it consistent with other two.

Target:
protected List<Object> identifyClearGarbage(Object locator) { return new ArrayList<>(locatorStore.clearUnsafe()); }
Source:
START public List<Object> identifyPutGarbage(Object locator, K key, V value) { END List<Object> garbage = new ArrayList<>(); garbage.addAll(locatorStore.addUnsafe(key, (SMRRecordLocator) locator)); return garbage; } Make them consistent with CorfuTable.

Target:
public List<Object> identifyPutGarbage(Object locator, K key, V value) { return new ArrayList<>(locatorStore.addUnsafe(key, (SMRRecordLocator) locator)); }
Source:
protected void clearIndex() { indexSpec.clear(); secondaryIndexes.clear(); START indexGenerationFailed = true; END } should `indexGenerationFailed` be volatile or AtomicBoolean?

Target:
protected void clearIndex() { indexSpec.clear(); secondaryIndexes.clear(); }
Source:
static ILogData getLogData(CorfuRuntime runtime, boolean loadInCache, long address) { if (loadInCache) { return runtime.getAddressSpaceView().read(address); } else { START return runtime.getAddressSpaceView().fetch(address, false); END } } Why does caching determine the behavior of the fetch? Why not handle the trimmed exception on the higher level. This seems like overloaded semantics to me.

Target:
static ILogData getLogData(CorfuRuntime runtime, boolean loadInCache, long address) { if (loadInCache) { return runtime.getAddressSpaceView().read(address); } else { return runtime.getAddressSpaceView().fetch(address); } }
Source:
protected ILogData read(final long address, long readStartTime) { try { if (System.currentTimeMillis() - readStartTime < runtime.getParameters().getHoleFillTimeout().toMillis()) { return runtime.getAddressSpaceView().read(address); } return runtime.getAddressSpaceView() START .read(Collections.singleton(address)) END .get(address); } catch (TrimmedException te) { processTrimmedException(te); throw te; } } Why is this behavior changed? It used to be NOT waitForWrite, but now it waits instead. Is that true?

Target:
protected ILogData read(final long address, long readStartTime) { try { if (System.currentTimeMillis() - readStartTime < runtime.getParameters().getHoleFillTimeout().toMillis()) { return runtime.getAddressSpaceView().read(address); } return runtime.getAddressSpaceView() .read(Collections.singleton(address), false, false) .get(address); } catch (TrimmedException te) { processTrimmedException(te); throw te; } }
Source:
public CorfuGuidGenerator(CorfuRuntime rt) { runtime = rt; try { START distributedCounter = (SMRMap<Integer, Long>) END (rt.getObjectsView().build() .setType(SMRMap.class) .setStreamName(GUID_STREAM_NAME) .open()); } catch (Exception e) { log.error("Failed to initialize CorfuGuidGenerator", e); throw e; } } Why try/catch? just let it fail. Also, the cast is not necessary.

Target:
public CorfuGuidGenerator(CorfuRuntime rt) { runtime = rt; distributedCounter = rt.getObjectsView().build() .setType(SMRMap.class) .setStreamName(GUID_STREAM_NAME) .open(); }
Source:
START public CorfuTable(IndexRegistry<K, V> indices, Map<K, V> mapImpl) { END indices.forEach(index -> { secondaryIndexes.put(index.getName().get(), new HashMap<>()); indexSpec.add(index); }); log.info("CorfuTable: creating CorfuTable with the following indexes: {}", secondaryIndexes.keySet().toString()); mainMap = mapImpl; } It might be cleaner to pass a type and not an instance. https://stackoverflow.com/questions/3574065/instantiate-a-class-object-with-constructor-that-accepts-a-string-parameter

Target:
public CorfuTable(IndexRegistry<K, V> indices, Map<K, V> mapImpl) { indices.forEach(index -> { secondaryIndexes.put(index.getName().get(), new HashMap<>()); indexSpec.add(index); }); log.info("CorfuTable: creating CorfuTable with the following indexes: {}", secondaryIndexes.keySet()); mainMap = mapImpl; }
Source:
public static ISerializer getSerializer(Byte type) { if (type <= SYSTEM_SERIALIZERS_COUNT) { if (serializersMap.containsKey(type)) { return serializersMap.get(type); } } else { START if (customSerializers.containsKey(type)) { END return customSerializers.get(type); } } log.error("Serializer with type code not found. Please check custom serializers " + "for this client.", type.intValue()); throw new SerializerException(type); } Please combine and remove the nested if.

Target:
public static ISerializer getSerializer(Byte type) { if (type <= SYSTEM_SERIALIZERS_COUNT) { if (serializersMap.containsKey(type)) { return serializersMap.get(type); } } else if (customSerializers.containsKey(type)) { return customSerializers.get(type); } log.error("Serializer with type code not found. Please check custom serializers " + "for this client.", type.intValue()); throw new SerializerException(type); }
Source:
public LogMetadata() { this.globalTail = Address.NON_ADDRESS; this.streamTails = new HashMap(); START this.streamsAddressSpaceMap = new HashMap(); END } `this.streamsAddressSpaceMap = new HashMap<>();`

Target:
public LogMetadata() { this.globalTail = Address.NON_ADDRESS; this.streamTails = new HashMap(); this.streamsAddressSpaceMap = new HashMap<>(); }
Source:
START public Long getLogTail() { END return logMetadata.getGlobalTail(); } please use `long`

Target:
public long getLogTail() { return logMetadata.getGlobalTail(); }
Source:
private void prefixTrim(CorfuPayloadMsg<TrimRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { try { TrimRequest req = msg.getPayload(); START batchWriter.prefixTrim(new Token(msg.getEpoch(), req.getAddress().getSequence())); END r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); } catch (TrimmedException ex) { r.sendResponse(ctx, msg, CorfuMsgType.ERROR_TRIMMED.msg()); } } The token is not persisted and this new code doesn't use the epoch. I suggest you drop the Token usage instead of transforming it.

Target:
private void prefixTrim(CorfuPayloadMsg<TrimRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { try { TrimRequest req = msg.getPayload(); batchWriter.prefixTrim(req.getAddress().getSequence(), msg.getEpoch()); r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); } catch (TrimmedException ex) { r.sendResponse(ctx, msg, CorfuMsgType.ERROR_TRIMMED.msg()); } }
Source:
public synchronized void trimCache(CorfuPayloadMsg<Long> msg, ChannelHandlerContext ctx, IServerRouter r) { log.info("trimCache: Starting cache eviction"); if (trimMark < msg.getPayload()) { // Advance the trim mark, if the new trim request has a higher trim mark. trimMark = msg.getPayload(); } START cache.invalidateUpTo(trimMark); END r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); } If the trim mark doesn't change why do you still iterate the cache ?

Target:
public synchronized void trimCache(CorfuPayloadMsg<Long> msg, ChannelHandlerContext ctx, IServerRouter r) { log.info("trimCache: Starting cache eviction"); if (trimMark < msg.getPayload()) { // Advance the trim mark, if the new trim request has a higher trim mark. trimMark = msg.getPayload(); cache.invalidateUpTo(trimMark); } r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); }
Source:
public long getStartingAddress() { if (startingAddress.get() == Address.NON_ADDRESS) { START long dbStartingAddress = Optional.ofNullable(dataStore.get(STARTING_ADDRESS_RECORD)).orElse(ZERO_ADDRESS); END startingAddress.set(dbStartingAddress); } return startingAddress.get(); } can you change this name, let's not use db, maybe use trimMark.

Target:
public long getStartingAddress() { if (startingAddress.get() == Address.NON_ADDRESS) { startingAddress.set(dataStore.get(STARTING_ADDRESS_RECORD, ZERO_ADDRESS)); } return startingAddress.get(); }
Source:
public AbstractViewTest() { // Force all new CorfuRuntimes to override the getRouterFn CorfuRuntime.overrideGetRouterFunction = this::getRouterFunction; final Duration holeFillTimeout = Duration.ofSeconds(5); runtime = CorfuRuntime.fromParameters(CorfuRuntimeParameters.builder() .nettyEventLoop(NETTY_EVENT_LOOP) START .holeFillTimeout(holeFillTimeout) END .build()); // Default number of times to read before hole filling to 0 // (most aggressive, to surface concurrency issues). runtime.getParameters().setHoleFillRetry(0); } Should this change be moved to #1763 ?

Target:
public AbstractViewTest() { // Force all new CorfuRuntimes to override the getRouterFn CorfuRuntime.overrideGetRouterFunction = this::getRouterFunction; runtime = CorfuRuntime.fromParameters(CorfuRuntimeParameters.builder() .nettyEventLoop(NETTY_EVENT_LOOP) .build()); // Default number of times to read before hole filling to 0 // (most aggressive, to surface concurrency issues). runtime.getParameters().setHoleFillRetry(0); }
Source:
public void gc(long trimMark) { START Timer.Context vloGcDuration = VloMetricsHelper.getVloGcContext(); END long ts = lock.writeLock(); try { pendingUpcalls.removeIf(e -> e < trimMark); upcallResults.entrySet().removeIf(e -> e.getKey() < trimMark); smrStream.gc(trimMark); } finally { lock.unlock(ts); if (vloGcDuration != null) { vloGcDuration.stop(); } } } Can you move this and the lock acquisition to within the try lock? To be consistent with other places in the same file where the lock is acquired in the lock.

Target:
public void gc(long trimMark) { long ts = 0; try (Timer.Context vloGcDuration = VloMetricsHelper.getVloGcContext()) { ts = lock.writeLock(); pendingUpcalls.removeIf(e -> e < trimMark); upcallResults.entrySet().removeIf(e -> e.getKey() < trimMark); smrStream.gc(trimMark); } finally { lock.unlock(ts); } }
Source:
START private void handleEviction(long address, ILogData entry, RemovalCause cause) { END log.trace("Eviction[{}]: {}", address, cause); streamLog.release(address, (LogData) entry); } What if the implementations of release changes from no op?

Target:
private void handleEviction(long address, ILogData entry, RemovalCause cause) { log.trace("Eviction[{}]: {}", address, cause); }
Source:
private long getCompactionCounter() { final Timer compactionTimer = metricRegistry.timer(StreamLogCompaction.STREAM_COMPACT_METRIC); START return compactionTimer == null ? END 0 : compactionTimer.getCount(); } As I know, if timer doesn't exists it will be created, so no need to check for null

Target:
private long getCompactionCounter() { return metricRegistry .timer(StreamLogCompaction.STREAM_COMPACT_METRIC) .getCount(); }
Source:
START public synchronized void sealServerWithEpoch(long epoch) { END batchWriter.waitForSealComplete(epoch); log.info("LogUnit sealServerWithEpoch: sealed and flushed with epoch {}", epoch); } why is this synchronized ?

Target:
public void sealServerWithEpoch(long epoch) { batchWriter.waitForSealComplete(epoch); log.info("LogUnit sealServerWithEpoch: sealed and flushed with epoch {}", epoch); }
Source:
public List<AbstractServer> getServers() { START return ImmutableList.copyOf(servers); END } What's the point of returning immutable copies, why not just make the class field immutable and return that?

Target:
public List<AbstractServer> getServers() { return servers; }
Source:
private boolean canHandleReconfigurations() { // We check for the following condition here: If the node is NOT a part of the // current layout, it should not attempt to change layout. Layout layout = serverContext.getManagementLayout(); START if (!layout.getAllServersNodes().contains(getLocalEndpoint())) { END return false; } return true; } it should be getAllServers or getAllServerNodes

Target:
private boolean canHandleReconfigurations() { // We check for the following condition here: If the node is NOT a part of the // current layout, it should not attempt to change layout. Layout layout = serverContext.getManagementLayout(); return layout.getAllServersNodes().contains(getLocalEndpoint()); }
Source:
public CorfuTable() { this(IndexRegistry.empty()); START log.warn("CorfuTable: Creating a table without secondary indexes! Secondary index lookup" END + " will fail."); } I suggest that this message is change to "table created with the following indexes" as opposed to printing the warning.

Target:
public CorfuTable() { this(IndexRegistry.empty()); }
Source:
private void consumeOperationQueue() { // Assign a worker for each thread in the pool for (int i = 0; i < numThreads; i++) { workers.execute(() -> { START while (!operationQueueLock && !operationQueue.isEmpty()) { END try { Operation op = operationQueue.take(); op.execute(); } catch (Exception e) { log.error("Operation failed with", e); } } }); } } There might be a serious problem here: once any of these two checks failed, the thread will finish and exit, but we expect it to block until the fillOperationQueue put more operations into the queue and continue consuming, right? I think that's why we are using a blocking queue.

Target:
private void consumeOperationQueue() { // Assign a worker for each thread in the pool for (int i = 0; i < numThreads; i++) { workers.execute(() -> { while (true) { if (!operationQueueLock && !operationQueue.isEmpty()) { try { Operation op = operationQueue.take(); op.execute(); } catch (Exception e) { log.error("Operation failed with", e); } } } }); } }
Source:
public void shutdown() { executor.shutdownNow(); try { executor.awaitTermination(ServerContext.SHUTDOWN_TIMER.getSeconds(), TimeUnit.SECONDS); } catch (InterruptedException ie) { log.debug("Orchestrator executor awaitTermination interrupted : {}", ie); Thread.currentThread().interrupt(); } START getRuntime.cleanup(CorfuRuntime::shutdown); END log.info("Orchestrator shutting down."); } The management server already shuts this down. It shuts down the services using this first i.e., the orchestrator and the management service and then finally the runtime. Shutting this down here will only create a new instance by the management service if that hasn't been shut down yet.

Target:
public void shutdown() { executor.shutdownNow(); try { executor.awaitTermination(ServerContext.SHUTDOWN_TIMER.getSeconds(), TimeUnit.SECONDS); } catch (InterruptedException ie) { log.debug("Orchestrator executor awaitTermination interrupted : {}", ie); Thread.currentThread().interrupt(); } log.info("Orchestrator shutting down."); }
Source:
private void updateLocalMetrics() { START suppressExceptions(() -> { END // Initializing the status of components // No need to poll unless node is bootstrapped. Layout layout = serverContext.copyManagementLayout(); if (layout == null) { return; } // Build and replace existing locally stored nodeMetrics localServerMetrics = new ServerMetrics(NodeLocator.parseString(getLocalEndpoint()), queryLocalSequencerMetrics(layout)); }); } i do not think wrapping should be here . It should be at scheduling level. The problem is that scheduler is finicky.

Target:
private void updateLocalMetrics() { // Initializing the status of components // No need to poll unless node is bootstrapped. Layout layout = serverContext.copyManagementLayout(); if (layout == null) { return; } // Build and replace existing locally stored nodeMetrics localServerMetrics = new ServerMetrics(NodeLocator.parseString(getLocalEndpoint()), queryLocalSequencerMetrics(layout)); }
Source:
protected UUID sendRequest(@Nonnull ManagementClient managementClient) throws TimeoutException { // Select the current tail node and send an add node request to the orchestrator CreateWorkflowResponse resp = managementClient.addNodeRequest(nodeForWorkflow); START log.debug("sendRequest: requested to add on orchestrator {}:{}", END nodeForWorkflow, managementClient.getRouter().getHost(), managementClient.getRouter().getPort()); return resp.getWorkflowId(); } You can leave this as info. It is helpful for debugging.

Target:
protected UUID sendRequest(@Nonnull ManagementClient managementClient) throws TimeoutException { // Select the current tail node and send an add node request to the orchestrator CreateWorkflowResponse resp = managementClient.addNodeRequest(nodeForWorkflow); log.info("sendRequest: requested to add on orchestrator {}:{}", nodeForWorkflow, managementClient.getRouter().getHost(), managementClient.getRouter().getPort()); return resp.getWorkflowId(); }
Source:
public boolean hasNext() { if (currInd < maxInd) { return true; START } else { END return false; } } I believe this is unnecessary expensive, why do you need to sort every time you resolve a new delta? Also, can you add a sanity check to make sure the boundaries are correct (addresses[0] > this.addresses[last ind]) and maybe during tail traversal you can make sure that the backpointer is always decreasing.

Target:
public boolean hasNext() { if (currInd.get() < maxInd.get()) { return true; } else { return false; } }
Source:
public synchronized <T> void put(Class<T> tclass, String prefix, String key, T value) { START String json = JsonUtils.parser.toJson(value, tclass); END T tmpVal = JsonUtils.parser.fromJson(json, tclass); DataStoreKey dsk = new DataStoreKey(getKey(prefix, key), tclass); cache.put(dsk, tmpVal); } Is this parse to and from JSON to clone the object?

Target:
public synchronized <T> void put(Class<T> tclass, String prefix, String key, T value) { cache.put(getKey(prefix, key), value); }
Source:
public AddNodeWorkflow(Request request) { this.id = UUID.randomUUID(); this.request = (AddNodeRequest) request; START actions = Arrays.asList(new BootstrapNode(), END new AddNodeToLayout(), new StateTransfer(), new MergeSegments()); } Can you use a ImmutableList (Guava)?

Target:
public AddNodeWorkflow(Request request) { this.id = UUID.randomUUID(); this.request = (AddNodeRequest) request; actions = ImmutableList.of(new BootstrapNode(), new AddNodeToLayout(), new StateTransfer(), new MergeSegments()); }
Source:
void handleQuery(CorfuPayloadMsg<OrchestratorRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { QueryRequest req = (QueryRequest) msg.getPayload().getRequest(); Response resp; if (activeWorkflows.contains(req.getId())) { resp = new QueryResponse(true); START } else { END resp = new QueryResponse(false); } r.sendResponse(ctx, msg, CorfuMsgType.ORCHESTRATOR_RESPONSE .payloadMsg(new OrchestratorResponse(resp ))); } does the queryResponse not return any status of the workflow or it's actions ?

Target:
void handleQuery(CorfuPayloadMsg<OrchestratorRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { QueryRequest req = (QueryRequest) msg.getPayload().getRequest(); Response resp; if (activeWorkflows.values().contains(req.getId())) { resp = new QueryResponse(true); } else { resp = new QueryResponse(false); } r.sendResponse(ctx, msg, CorfuMsgType.ORCHESTRATOR_RESPONSE .payloadMsg(new OrchestratorResponse(resp ))); }
Source:
public Layout getCurrentLayout() { while (true) { try { return runtime.layout.get(); START } catch (SystemUnavailableException sue) { END throw sue; } catch (Exception ex) { log.warn("Error executing remote call, invalidating view and retrying in {}s", runtime.retryRate, ex); runtime.invalidateLayout(); try { Thread.sleep(runtime.retryRate * 1000); } catch (InterruptedException ie) { throw new UnrecoverableCorfuInterruptedError("Interrupted while fetching layout", ie); } } } } This shouldn't be necessary, the error will not be caught by the exception catch block below

Target:
public Layout getCurrentLayout() { while (true) { try { return runtime.layout.get(); } catch (Exception ex) { log.warn("Error executing remote call, invalidating view and retrying in {}s", runtime.retryRate, ex); runtime.invalidateLayout(); try { Thread.sleep(runtime.retryRate * 1000); } catch (InterruptedException ie) { throw new UnrecoverableCorfuInterruptedError("Interrupted while fetching layout", ie); } } } }
Source:
public Collection<Object> getByIndex(@Nonnull F indexFunction, I index) { return indexFunction.getProjectionFunction() .generateProjection(index, indexMap START .getOrDefault(indexFunction, ImmutableMultimap.of()).get(index)); END } I tried a bunch of things and the final tweak that I wanted to run by you is that if instead of immutable data structure we provide a fail-safe iterator we will not have to make copies, which are very slow. So effectively if the index was a ConcurrentHashMap (used only for it's failsafe iterator) instead of a HashMap, we will not need to make a copy of the collection. This speeds up the retrieval multifold.

Target:
public @Nonnull Collection<Object> getByIndex(@Nonnull F indexFunction, I index) { return getByIndex(indexFunction, indexFunction.getProjectionFunction(), index); }
Source:
public V put(@ConflictParameter K key, V value) { V previous = mainMap.put(key, value); // If we have index functions, update the secondary indexes. START if (indexFunctions.isEmpty()) { END unmapSecondaryIndexes(key, previous); mapSecondaryIndexes(key, value); } return previous; } if !indexFunctions.isEmpty()

Target:
public V put(@ConflictParameter K key, V value) { V previous = mainMap.put(key, value); // If we have index functions, update the secondary indexes. if (!indexFunctions.isEmpty()) { unmapSecondaryIndexes(key, previous); mapSecondaryIndexes(key, value); } return previous; }
Source:
public TrimmedException() { START address = -1; END } Can you use the Address.NON_EXIST constant?

Target:
public TrimmedException() { }
Source:
public ServerNotReadyException() { START super("Server not ready to accept messages."); END } Exception already indicates that?

Target:
public ServerNotReadyException() { }
Source:
START public synchronized long getTailSegment() { END Long tailSegment = dataStore.get(Long.class, PREFIX_TAIL_SEGMENT, KEY_TAIL_SEGMENT); return tailSegment == null ? 0 : tailSegment; } why do you need this synchronized. I remember the datastore gave you that. I might be wrong.

Target:
public long getTailSegment() { Long tailSegment = dataStore.get(Long.class, PREFIX_TAIL_SEGMENT, KEY_TAIL_SEGMENT); return tailSegment == null ? 0 : tailSegment; }
Source:
private synchronized void safeUpdateLayout(Layout layout) { // Cannot update with a null layout. if (layout == null) return; // Update if new layout has a higher epoch than the existing layout. // Or if the cluster ID is different. if (latestLayout == null || layout.getEpoch() > latestLayout.getEpoch() || START !layout.getClusterId().equals(latestLayout.getClusterId())) { END latestLayout = layout; // Persisting this new updated layout setCurrentLayout(latestLayout); } } Change the layout any time cluster ID doesn't match?...That looks very permissive.

Target:
private synchronized void safeUpdateLayout(Layout layout) { // Cannot update with a null layout. if (layout == null) { return; } // Update only if new layout has a higher epoch than the existing layout. if (latestLayout == null || layout.getEpoch() > latestLayout.getEpoch()) { latestLayout = layout; // Persisting this new updated layout setCurrentLayout(latestLayout); } }
Source:
public <R> R access(ICorfuSMRAccess<R, T> accessMethod, Object[] conflictObject) { R value; START boolean isEnabled = MetricsUtils.isMetricsCollectionEnabled(); END Timer.Context context = MetricsUtils.getConditionalContext(isEnabled, timerAccess); try { value = accessInner(accessMethod, conflictObject, isEnabled); } finally { MetricsUtils.stopConditionalContext(isEnabled, context); } return value; } Once again, I don't understand why obtain the isEnabled boolean from MetricUtils, only to send it back to MetricUtils.getConditionalContext(). Same below in all instances.

Target:
public <R> R access(ICorfuSMRAccess<R, T> accessMethod, Object[] conflictObject) { boolean isEnabled = MetricsUtils.isMetricsCollectionEnabled(); try (Timer.Context context = MetricsUtils.getConditionalContext(isEnabled, timerAccess)){ return accessInner(accessMethod, conflictObject, isEnabled); } }
Source:
public CompletableFuture<Boolean> writeStream(long address, Map<UUID, Long> streamAddresses, Object object) { Timer.Context context = getTimerContext("writeStreamObject"); ByteBuf payload = ByteBufAllocator.DEFAULT.buffer(); Serializers.CORFU.serialize(object, payload); CompletableFuture<Boolean> cf = writeStream(address, streamAddresses, payload); START return context == null ? cf : cf.thenApply(x -> { context.stop(); return x; }); END } same. I'll stop repeating.

Target:
public CompletableFuture<Boolean> writeStream(long address, Map<UUID, Long> streamAddresses, Object object) { Timer.Context context = getTimerContext("writeStreamObject"); ByteBuf payload = ByteBufAllocator.DEFAULT.buffer(); Serializers.CORFU.serialize(object, payload); CompletableFuture<Boolean> cf = writeStream(address, streamAddresses, payload); return cf.thenApply(x -> { context.stop(); return x; }); }
Source:
START public synchronized void handleHearbeatRequest(CorfuMsg msg, ChannelHandlerContext ctx, IServerRouter r) { END // Currently builds a default instance of the model. // TODO: Collect metrics from Layout, Sequencer and LogUnit Servers. NodeMetrics nodeMetrics = NodeMetrics.getDefaultInstance(); r.sendResponse(ctx, msg, new CorfuPayloadMsg<>(CorfuMsgType.HEARTBEAT_RESPONSE, nodeMetrics.toByteArray())); } why is this synchronized ? I see all the message handlers are synchronized on the instance. Hopefully we have given enough thought to the class members to arrive at the conclusion that all external facing methods should be synchronized.

Target:
public void handleHearbeatRequest(CorfuMsg msg, ChannelHandlerContext ctx, IServerRouter r) { // Currently builds a default instance of the model. // TODO: Collect metrics from Layout, Sequencer and LogUnit Servers. NodeMetrics nodeMetrics = NodeMetrics.getDefaultInstance(); r.sendResponse(ctx, msg, new CorfuPayloadMsg<>(CorfuMsgType.HEARTBEAT_RESPONSE, nodeMetrics.toByteArray())); }
Source:
public synchronized long obtainSnapshotTimestamp() { START AbstractTransactionalContext atc = getRootContext(); END if (atc != null && atc != this) { // If we're in a nested transaction, the first read timestamp // needs to come from the root. return atc.getSnapshotTimestamp(); } else { // Otherwise, fetch a read token from the sequencer the linearize // ourselves against. long currentTail = builder.runtime .getSequencerView().nextToken(Collections.emptySet(), 0).getToken(); log.trace("Set first read timestamp for tx to {}", transactionID, currentTail); return currentTail; } } should be marked final

Target:
public synchronized long obtainSnapshotTimestamp() { final AbstractTransactionalContext atc = getRootContext(); if (atc != null && atc != this) { // If we're in a nested transaction, the first read timestamp // needs to come from the root. return atc.getSnapshotTimestamp(); } else { // Otherwise, fetch a read token from the sequencer the linearize // ourselves against. long currentTail = builder.runtime .getSequencerView().nextToken(Collections.emptySet(), 0).getToken(); log.trace("Set first read timestamp for tx to {}", transactionID, currentTail); return currentTail; } }
Source:
public void shutdown() { // Shutting the fault detector. isShutdown = true; failureDetectorService.shutdownNow(); // Shut down the Corfu Runtime. if (corfuRuntime != null) { corfuRuntime.shutdown(); } try { START failureDetectorService.awaitTermination(5, TimeUnit.SECONDS); END } catch (InterruptedException ie) { log.debug("failureDetectorService awaitTermination interrupted : {}", ie); } } What is the significance of this 5 second wait? Why not just do shutdownNow?

Target:
public void shutdown() { // Shutting the fault detector. failureDetectorService.shutdownNow(); // Shut down the Corfu Runtime. if (corfuRuntime != null) { corfuRuntime.shutdown(); } try { failureDetectorService.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException ie) { log.debug("failureDetectorService awaitTermination interrupted : {}", ie); } }
Source:
public PropertyEntry getShallowestProperty() { START if ( !propertyEntries.isEmpty() ) { END return first( propertyEntries ); } return null; } Is it our common rule? I mean invertring boolean condition? Maybe it's not so smart question :). I mean, maybe is little more readable? `if ( propertyEntries.isEmpty() ) { ` ` return null;` ` }` ` return first( propertyEntries) ;` `}`

Target:
public PropertyEntry getShallowestProperty() { if ( propertyEntries.isEmpty() ) { return null; } return first( propertyEntries ); }
Source:
public String toString() { START return element.getSimpleName().toString() + "( . )"; END } Why not just use the `element.toString()` instead? If we want to use something specific in the printing of the messager we should pass that in the arguments, and not do it in the `toString`. For debugging it would be much easier to just have `element.toString()` here.

Target:
public String toString() { return element.toString(); }
Source:
public Set<Type> getImportTypes() { Set<Type> types = new HashSet<Type>(); for ( MapperReference mapperReference : mapperReferences ) { START types.add( mapperReference.getType() ); END } for ( Annotation annotation : annotations ) { types.add( annotation.getType() ); } return types; } Use `mapperReference#getImportTypes()` instead

Target:
public Set<Type> getImportTypes() { Set<Type> types = new HashSet<Type>(); for ( MapperReference mapperReference : mapperReferences ) { types.addAll( mapperReference.getImportTypes() ); } for ( Annotation annotation : annotations ) { types.addAll( annotation.getImportTypes() ); } return types; }
Source:
AbstractAccessor(T element) { this.element = element; START if (element.getEnclosingElement().getKind() == ElementKind.CLASS) { END Element enclosingClass = element.getEnclosingElement(); boolean isBuilder = enclosingClass.getEnclosingElement().getKind() == ElementKind.CLASS && MappedByBuilderPrism.getInstanceOn( enclosingClass.getEnclosingElement() ) != null; this.builderType = isBuilder ? enclosingClass.asType() : null; } else { this.builderType = null; } } This means that we can't build interfaces with builders right?

Target:
AbstractAccessor(T element ) { this( element, false ); }
Source:
START public boolean isAbstract() { END return typeElement != null && typeElement.getKind().isClass() && typeElement.getModifiers().contains( Modifier.ABSTRACT ); } Would that actually kick in for interfaces, too? I don't think we need keep the two cases apart, interfaces are just a form of abstract type. In the error message we could say "result type may not be an abstract class nor interface".

Target:
public boolean isAbstract() { return typeElement != null && typeElement.getModifiers().contains( Modifier.ABSTRACT ); }
Source:
START public boolean isAbstract() { END return (declaringMapper != null && declaringMapper.getTypeElement().getKind().isInterface()) || executable.getModifiers().contains( Modifier.ABSTRACT ); } This one needs to represent whether an implementation will be created for this method, right? Why don't we do `return overridesMethod() || !isDefault()`? Or maybe we need to do something else, as this will pick up Java 8 default methods. I think that we need to consider the Java 8 default methods the same way as we consider non abstract methods.

Target:
public boolean isAbstract() { return executable.getModifiers().contains( Modifier.ABSTRACT ); }
Source:
START public Parameter(String name, Type type, boolean mappingTarget, boolean targetType, boolean mappingContext) { END // issue #909: FreeMarker doesn't like "values" as a parameter name this.name = "values".equals( name ) ? "values_" : name; this.originalName = name; this.type = type; this.mappingTarget = mappingTarget; this.targetType = targetType; this.mappingContext = mappingContext; } I'm wondering whether we should create sub-types instead of using the booleans.

Target:
private Parameter(String name, Type type, boolean mappingTarget, boolean targetType, boolean mappingContext) { // issue #909: FreeMarker doesn't like "values" as a parameter name this.name = "values".equals( name ) ? "values_" : name; this.originalName = name; this.type = type; this.mappingTarget = mappingTarget; this.targetType = targetType; this.mappingContext = mappingContext; }
Source:
private String getName(Type sourceType, Type targetType) { String fromName = getName( sourceType ); String toName = getName( targetType ); String with = nullValueMappingStrategy != null ? START "WithNvms" + camelizeEnumConstant( nullValueMappingStrategy ) : ""; END return Strings.decapitalize( fromName + "To" + toName + with ); } "camelize"... that's flowerly... 🐫 👍

Target:
private String getName(Type sourceType, Type targetType ) { String fromName = getName( sourceType ); String toName = getName( targetType ); return Strings.decapitalize( fromName + "To" + toName ); }
Source:
private boolean isExecutableType(TypeMirror accessorType) { START return accessorType.getKind() == TypeKind.EXECUTABLE && accessorType instanceof ExecutableType; END } I reckon the && is not needed, right?

Target:
private boolean isExecutableType(TypeMirror accessorType) { return accessorType.getKind() == TypeKind.EXECUTABLE; }
Source:
public static void cleanup() { Integer level = LEVEL.get(); fireMethodCalled( level, "cleanup", null, null ); if ( level.intValue() == 1 ) { MAPPING.set( null ); LEVEL.set( null ); } else { START LEVEL.set( level.intValue() - 1 ); END } } not needed unboxing

Target:
public static void cleanup() { Integer level = LEVEL.get(); fireMethodCalled( level, "cleanup", null, null ); if ( level == 1 ) { MAPPING.set( null ); LEVEL.set( null ); } else { LEVEL.set( level - 1 ); } }
Source:
public Set<Type> getImportTypes() { START Set<Type> imported = new HashSet<Type>( getAssignment().getImportTypes().size() + 1 ); END imported.addAll( getAssignment().getImportTypes() ); imported.add( enumType ); return imported; } That would require a resize of the underlying map, as the default load factor is 0.75... Let's just use `new HashSet<Type>( getAssignment().getImportTypes() )` followed by just the `.add( enumType )`.

Target:
public Set<Type> getImportTypes() { Set<Type> imported = new HashSet<Type>( getAssignment().getImportTypes() ); imported.add( enumType ); return imported; }
Source:
public ExecutableType getMethodType(TypeElement includingType, ExecutableElement method) { DeclaredType asType = (DeclaredType) replaceTypeElementIfNecessary( elementUtils, includingType ).asType(); START TypeMirror asMemberOf = SpecificCompilerWorkarounds.asMemberOf( asType, method, typeUtils, elementUtils ); END ExecutableType methodType = asMemberOf.accept( new ExecutableTypeRetrievalVisitor(), null ); return methodType; } Should we add a CS rule to make sure that nowhere in our code base the original `isMemberOf()` is invoked? IIRC, they provide a way to fail the build if specific methods are invoked.

Target:
public ExecutableType getMethodType(TypeElement includingType, ExecutableElement method) { DeclaredType asType = (DeclaredType) replaceTypeElementIfNecessary( elementUtils, includingType ).asType(); TypeMirror asMemberOf = typeUtils.asMemberOf( asType, method ); return (ExecutableType) asMemberOf; }
Source:
protected List<Annotation> getTypeAnnotations(Mapper mapper) { if ( mapper.getDecorator() == null ) { return Arrays.asList( singleton(), named() ); } else { START return Collections.singletonList( namedDelegate( mapper ) ); END } } You need to add the annotation here as well, as otherwise the delegate (i.e. the actual mapper implementation) for a decorator does not get the `@Singleton` annotation.

Target:
protected List<Annotation> getTypeAnnotations(Mapper mapper) { if ( mapper.getDecorator() == null ) { return Arrays.asList( singleton(), named() ); } else { return Arrays.asList( singleton(), namedDelegate( mapper ) ); } }
Source:
public void analyze() { START for ( Node node : nodes.values() ) { END depthFirstSearch( node ); } } This changes the state of the instance so that calling addNode would be illegal after this. Would it make sense to prevent that? Either by API or by adding a check in addNode?

Target:
private void analyze() { for ( Node node : nodes.values() ) { depthFirstSearch( node ); } }
Source:
private List<String> getCurrentCycle(Node start) { List<String> cycle = new ArrayList<String>(); boolean inCycle = false; for ( Node n : currentPath ) { START if ( n.getName().equals( start.getName() ) ) { END inCycle = true; } if ( inCycle ) { cycle.add( n.getName() ); } } return cycle; } you could even check for `n == start`, right? Or use `n.equals( start )`, as your equals-implementation in Node checks for reference equality first.

Target:
private List<String> getCurrentCycle(Node start) { List<String> cycle = new ArrayList<String>(); boolean inCycle = false; for ( Node n : currentPath ) { if ( !inCycle && n.equals( start ) ) { inCycle = true; } if ( inCycle ) { cycle.add( n.getName() ); } } return cycle; }
Source:
public PlayerNetworkComponent getNetwork() { START return getExact(PlayerNetworkComponent.class); END } This kills the ability for Vanilla to extend PlayerNetworkComponent.

Target:
public PlayerNetworkComponent getNetwork() { return get(PlayerNetworkComponent.class); }
Source:
public boolean execute(BlockComponentHolder component) { try { for (Component c : component.values()) { if (c.canTick()) { START c.tick(dt); END } } } catch (Exception e) { Spout.getLogger().log(Level.SEVERE, "Unhandled exception while ticking block component", e); } return true; } Formatting is off, and the try should only cover the if (canTick(dt) { c.tick(dt); } so that 1 bad component does not prevent other components from receiving ticks.

Target:
public boolean execute(BlockComponentHolder component) { for (Component c : component.values()) { try { if (c.canTick()) { c.tick(dt); } } catch (Exception e) { Spout.getLogger().log(Level.SEVERE, "Unhandled exception while ticking block component", e); } } return true; }
Source:
START public synchronized DateFormat get() { END DateFormat dateFormat = threadMap.get(Thread.currentThread()); if (dateFormat == null) { dateFormat = (DateFormat) templateFormat.clone(); threadMap.put(Thread.currentThread(), dateFormat); } return dateFormat; } @ztravis synchronized scope, can be more smaller, like below. ` private` final Object getDateFormatLock = new Object(); public DateFormat get() { DateFormat dateFormat; synchronized (getDateFormatLock) { dateFormat = (DateFormat) threadMap.get(Thread.currentThread()); } ... return dateFormat; } `

Target:
public DateFormat get() { DateFormat dateFormat = threadMap.get(Thread.currentThread()); if (dateFormat == null) { dateFormat = (DateFormat) templateFormat.clone(); threadMap.put(Thread.currentThread(), dateFormat); } return dateFormat; }
Source:
public void testPackagingRetrieve() throws LobException { String id = "1"; Packaging packaging = Packaging.retrieve(id, Lob.apiKey); assertEquals("1", packaging.getId()); assertEquals("Smart Packaging", packaging.getName()); START assertEquals("Automatically determined optimal packaging for safe and secure delivery", packaging.getDescription()); END assertEquals("packaging", packaging.getObject()); } I would not check the description string as it may change over time. I would just check if the description property exists. Ill merge once this is changed.

Target:
public void testPackagingRetrieve() throws LobException { String id = "1"; Packaging packaging = Packaging.retrieve(id, Lob.apiKey); assertEquals("1", packaging.getId()); assertEquals("Smart Packaging", packaging.getName()); assertTrue(packaging.getDescription().length() > 0); assertEquals("packaging", packaging.getObject()); }
Source:
public List<NodePropertyDescriptor> getNodePropertiesDescriptors() { DescriptorExtensionList<NodeProperty<?>, NodePropertyDescriptor> nodePropertyDescriptors = NodeProperty.all(); return nodePropertyDescriptors.stream() .filter(npd -> npd.isApplicable(vSphereCloudSlave.class)) START .collect(Collectors.toList()); END } I'm not hugely keen of the aesthetics on the syntax here but I presume that this is Java-8 syntax for applying the same filter? (I'm not asking for changes, just reassurances that this is "how it's normally done these days" as I've not seen that code pattern before)

Target:
public List<NodePropertyDescriptor> getNodePropertiesDescriptors() { List<NodePropertyDescriptor> result = new ArrayList<>(); DescriptorExtensionList<NodeProperty<?>, NodePropertyDescriptor> list = NodeProperty.all(); for (NodePropertyDescriptor npd : list) { if (npd.isApplicable(vSphereCloudSlave.class)) { result.add(npd); } } return result; }
Source:
public boolean filter(@CheckForNull Object context, @NonNull Descriptor descriptor) { START return !(descriptor instanceof vSphereCloudProvisionedSlave.DescriptorImpl); END } I'd go with the former. Where we've got ``` class C { class Inner { ... } ``` then code in class C that references class C.Inner should do so by saying `Inner` not `C.Inner`. ...but I'm still not entirely convinced that, even expressed like that, the code is doing what's needed, and the fact that this slipped through suggests that whatever testing you did, didn't pick this up.

Target:
public boolean filter(@CheckForNull Object context, @NonNull Descriptor descriptor) { return !(descriptor instanceof DescriptorImpl); }
Source:
private static Node provisionNewNode(final CloudProvisioningRecord whatWeShouldSpinUp, final String cloneName) throws VSphereException, FormException, IOException, InterruptedException { final vSphereCloudSlaveTemplate template = whatWeShouldSpinUp.getTemplate(); final vSphereCloudProvisionedSlave slave = template.provision(cloneName, StreamTaskListener.fromStdout()); // ensure Jenkins knows about us before we forget what we're doing, // otherwise it'll just ask for more. START Jenkins.get().addNode(slave); END return slave; } changing `Jenkins.getInstance()` and `Jenkins.getActiveInstance()` to `Jenkins.get()` is ok, as long as `get()` really is the right method in each situation - sometimes code uses different getters for good reasons. I'm not claiming that this code has good reasons, but it's a possibility one has to consider and I'd like to know what the justification is. However, any such changes are best done as a separate PR.

Target:
private static Node provisionNewNode(final CloudProvisioningRecord whatWeShouldSpinUp, final String cloneName) throws VSphereException, FormException, IOException, InterruptedException { final vSphereCloudSlaveTemplate template = whatWeShouldSpinUp.getTemplate(); final vSphereCloudProvisionedSlave slave = template.provision(cloneName, StreamTaskListener.fromStdout()); // ensure Jenkins knows about us before we forget what we're doing, // otherwise it'll just ask for more. Jenkins.getInstance().addNode(slave); return slave; }
Source:
public Map<String, Object> getData() { START return Collections.unmodifiableMap(this.data); END } unneeded

Target:
public Map<String, Object> getData() { return this.data; }
Source:
public String toString() { START return "Script " + this.name + " from version " + from + " to " + to; END } `from` and `to` can be null. ```suggestion return "Script " + this.name + (from != null ? " from version " + from : "") + (to != null ? " to " + to : ""); ```

Target:
public String toString() { return from != null && to != null ? "Script " + this.name + " from version " + from + " to " + to : "Script " + this.name; }
Source:
public void addExtraData(String variable, Object variableValue) { if (this.data == null) { START this.data = new HashMap<String, Object>(); END } this.data.put(variable, variableValue); } <String, Object> not needed.

Target:
public void addExtraData(String variable, Object variableValue) { if (this.data == null) { this.data = new HashMap<>(); } this.data.put(variable, variableValue); }
Source:
public void addProcessVariable(String variable, Object variableValue) { if (this.processVariables == null) { START this.processVariables = new HashMap<String, Object>(); END } this.processVariables.put(variable, variableValue); } <String, Object> not needed.

Target:
public void addProcessVariable(String variable, Object variableValue) { if (this.processVariables == null) { this.processVariables = new HashMap<>(); } this.processVariables.put(variable, variableValue); }
Source:
private List<ProcessInstance> startProcess(KieSession kieSession, String processId, int count) throws InterruptedException { List<ProcessInstance> piList = new ArrayList<ProcessInstance>(); for (int i = 0; i < count; i++) { START TimeUnit.MILLISECONDS.sleep(1000); END ProcessInstance pi = kieSession.startProcess(processId); if (pi != null) { piList.add(pi); } } return piList; } Reduce sleep time (probably a few milliseconds is enough)

Target:
private List<ProcessInstance> startProcess(KieSession kieSession, String processId, int count) throws InterruptedException { return this.startProcess(kieSession, processId, count, 0); }