auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Stream<Entry<K, V>> entryStream() { final ReadOptions readOptions = new ReadOptions(); // If ReadOptions.snapshot is given, the iterator will return data as of the snapshot. // If it is nullptr, the iterator will read from an implicit snapshot as of the time the // iterator is created. The implicit snapshot is preserved by pinning resource. readOptions.setSnapshot(null); final RocksDbEntryIterator entryIterator = new RocksDbEntryIterator(rocksDb.newIterator(readOptions), serializer); // It's necessary to use the RocksDbEntryIterator as try-with resource to ensure // the iterator is close, otherwise underlying RocksDB resources can leak Stream<Entry<K, V>> resStream = Streams.stream(entryIterator); resStream.onClose(entryIterator::close); return resStream; }

Target:
According to this: https://github.com/facebook/rocksdb/blob/master/java/src/main/java/org/rocksdb/ReadOptions.java#L11 I think we need to call `readOptions.close()` before returning to prevent memory leak. (dispose is deprecated, so using close())
Source:
long firstAddress() { if (cacheEntries.peek() == null) return Address.NOT_FOUND;; return cacheEntries.peek().txVersion; }

Target:
can we add an access specifier here?
Source:
private long firstAddress() { if (cacheEntries.peek() == null) return Address.NOT_FOUND; return cacheEntries.peek().txVersion; }

Target:
Please replace by `if(!cacheEntries.isEmpty())`
Source:
public long firstAddress() { if (cacheEntries.isEmpty()) return Address.NOT_FOUND; return cacheEntries.peek().txVersion; }

Target:
Please use curly brackets: https://stackoverflow.com/a/15786982
Source:
public static Config parse(Map<String, Object> opts) { int cacheSize = (int)(opts.containsKey("--sequencer-cache-size") ? Long.parseLong((String)opts.get("--sequencer-cache-size")) : DEFAULT_CACHE_SIZE); return Config.builder() .cacheSize(cacheSize) .build(); }

Target:
why parse into a long and then typecast to an integer? Can we use Integer.parseInt() instead?
Source:
private CorfuRuntime createDefaultRuntimeUsingFollowBackpointers() { CorfuRuntime runtime = createRuntime(DEFAULT_ENDPOINT); runtime.getParameters().setFollowBackpointersEnabled(false) .setCacheDisabled(false); return runtime; }

Target:
this one is intended to use the follow backpointers implementation, so it should be set to true.
Source:
public boolean getBindToAllInterfaces() { if (getNetworkInterface() != null || getHostAddress() != null) { return false; } else { return true; } }

Target:
![Codacy](https://app.codacy.com/assets/images/favicon.png) Issue found: [Avoid unnecessary if..then..else statements when returning booleans](https://app.codacy.com/app/CorfuDB/CorfuDB/pullRequest?prid=4662120)
Source:
void processRequest(CorfuMsg msg, ChannelHandlerContext ctx, IServerRouter r) { getHandler().handle(msg, ctx, r); }

Target:
![Codacy](https://app.codacy.com/assets/images/favicon.png) Issue found: [Use explicit scoping instead of the default package private level](https://app.codacy.com/app/annymartinez.m/CorfuDB/pullRequest?prid=4651438)
Source:
public void addIndexerToCorfuTableStream(String streamName, IndexRegistry indexRegistry) { UUID streamId = CorfuRuntime.getStreamID(streamName); SMRObject.Builder ob = SMRObject.builder() .runtime(runtime) .setType(CorfuTable.class) .setArguments(indexRegistry) .setStreamID(streamId); addCustomTypeStream(streamId, ob); }

Target:
use `type(CorfuTable)` instead of setType
Source:
public void stop() { if (!isRunning.get()) { log.info("Garbage informer had been stopped."); return; } gcScheduler.shutdownNow(); log.info("Garbage informer is stopped."); isRunning.set(false); }

Target:
I think it's better to use compareAndSet just as what you did in start()
Source:
public DetectorTask restoreRedundancy(Layout layout){ return restoreRedundancyAndMergeSegments(layout); }

Target:
what's the point for the wrapper method?
Source:
public void impl(@Nonnull CorfuRuntime runtime) throws Exception { runtime.invalidateLayout(); Layout layout = new Layout(runtime.getLayoutView().getLayout()); runtime.getLayoutManagementView().removeNode(layout, request.getEndpoint()); }

Target:
The orchestrator will pass down a connected client (i.e. it will have a layout ready) when it creates a workflow, why is this needed?
Source:
public static boolean canMergeSegments(Layout layout) { if (layout.getSegments().size() == 1) { return false; } else { int firstSegmentIndex = 0; int secondSegmentIndex = 1; return Sets.difference( layout.getSegments().get(secondSegmentIndex).getAllLogServers(), layout.getSegments().get(firstSegmentIndex).getAllLogServers()).isEmpty(); } }

Target:
final int
Source:
public StreamPerformanceTest() { metricRegistry = CorfuRuntime.getDefaultMetrics(); producerTimer = metricRegistry.timer(METRIC_PREFIX + "stream-producer"); consumerTimer = metricRegistry.timer(METRIC_PREFIX + "stream-consumer"); }

Target:
![Codacy](https://app.codacy.com/assets/images/favicon.png) Issue found: [Possible unsafe assignment to a non-final static field in a constructor.](https://app.codacy.com/app/annymartinez.m/CorfuDB/pullRequest?prid=4651454)
Source:
String getKey() { return keySet.get(random.nextInt(keySet.size())); }

Target:
![Codacy](https://app.codacy.com/assets/images/favicon.png) Issue found: [Use explicit scoping instead of the default package private level](https://app.codacy.com/app/annymartinez.m/CorfuDB/pullRequest?prid=4651454)
Source:
String generateValue() { return RandomStringUtils.random(valueSize, true, true); }

Target:
![Codacy](https://app.codacy.com/assets/images/favicon.png) Issue found: [Use explicit scoping instead of the default package private level](https://app.codacy.com/app/annymartinez.m/CorfuDB/pullRequest?prid=4651454)
Source:
public Entry<K, V> next() { checkInvariants(); if (hasNext()) { current = next; next = null; return current; } else { throw new NoSuchElementException(); } }

Target:
You can remove this since `hasNext` will call `checkInvariants`
Source:
private static CorfuRuntime getRuntimeAndConnect(String configurationString) { return CorfuRuntime.fromParameters(CorfuRuntime.CorfuRuntimeParameters.builder() .useFastLoader(false) .cacheDisabled(true) .tlsEnabled(true) .keyStore("/config/cluster-manager/corfu/private/keystore.jks") .ksPasswordFile("/config/cluster-manager/corfu/private/keystore.password") .trustStore("/config/cluster-manager/corfu/public/truststore.jks") .tsPasswordFile("/config/cluster-manager/corfu/public/truststore.password") .build()) .parseConfigurationString(configurationString) .connect(); }

Target:
Why the files are using these paths instead of a local file in the resource folder?
Source:
public static <K, V> TypeToken<CorfuTable<K, V>> getMapType() { return new TypeToken<CorfuTable<K, V>>() { }; }

Target:
Can you please revert this file. It will cause bunch of conflicts with my changes.
Source:
private void closeSegments(AbstractLogSegment... segments) { for (AbstractLogSegment segment : segments) { if (segment != null) { segment.close(); } } }

Target:
isn't it cleaner to keep this function as append?
Source:
public boolean contains(long address) { int retryCount = 0; while (true) { try { StreamLogSegment segment = segmentManager.getStreamLogSegment(address); return segment.contains(address); } catch (ClosedSegmentException e) { log.warn("Segment channel closed by compactor, retry for another time."); // Segment could be closed because of compaction, retry once. if (retryCount++ == CLOSE_SEGMENT_EXCEPTION_RETRY) { throw e; } } } }

Target:
the English here is a bit strange. Can we change to : '..., retry.'
Source:
void runConsumers() { for (int i = 0; i < numThreads; i++) { workers.execute(() -> { try { long start = System.nanoTime(); Operation op = operationQueue.take(); op.execute(); long latency = System.nanoTime() - start; System.out.println("nextToken request latency: " + latency); } catch (Exception e) { log.error("Operation failed with", e); } }); } }

Target:
Using System.out.println() is forbidden. Use a logger or output utility. [printLine]
Source:
CorfuRecord<V, M> getRecord(@Nonnull final String tableName, @Nonnull final K key) { return get(tableName, null, key); }

Target:
Should this be `return getRecord(tableName, null, key)`?
Source:
private String getTypeUrl(Descriptor descriptor) { return "type.googleapis.com/" + descriptor.getFullName(); }

Target:
Declare as final static..
Source:
private void cleanUpForRetry() { runtime.getAddressSpaceView().invalidateClientCache(); runtime.getObjectsView().getObjectCache().clear(); runtime.getStreamsView().getStreamCache().clear(); // Re ask for the Head, if it changes while we were trying. findAndSetLogHead(); findAndSetLogTail(); nextRead = logHead; resetAddressProcessed(); log.info("retry fastobject loader head " + logHead + " tail " + logTail); }

Target:
Should we add a validation that the head and tail chosen are chosen on the same epoch? Probably this is already taken care of by the inherent order of setting the head before the tail, but I think it would be safer to put this validation here.
Source:
private boolean cacheReadRequest(ReadOptions options) { if (runtime.getParameters().isCacheDisabled() && options.isClientCacheable()) { // TODO(Maithem): We can remove this once we have multi-level caches if (runtime.getParameters().getPriorityLevel() != PriorityLevel.HIGH) { // Avoid log flooding for background tasks (eg. checkpointer) log.warn("read: Runtime cache is disabled, but read request is requesting to cache"); } } return !runtime.getParameters().isCacheDisabled() && options.isClientCacheable(); }

Target:
On my old review it was suggested to have this log line, I would vote for just removing it and not making this distinction.
Source:
public int getGarbageSizeUpTo(long addressUpTo) { return streamIdToGarbageMap.values().stream() .flatMap(multiSMRGarbage -> multiSMRGarbage.values().stream()) .map(smrRecordGarbage -> smrRecordGarbage.getSmrEntrySize()) .reduce(0, (a, b) -> a + b); }

Target:
Why `addressUpTo` is not used? For your reference, following codes are what I used to use: ```java public int getGarbageSizeUpTo(long addressUpTo) { return streamIdToGarbageMap.values().stream() .map(multiSmr -> multiSmr.getGarbageSizeUpTo(addressUpTo)) .reduce(0, (a, b) -> a + b); } ```
Source:
default Long getGlobalAddress() { if (getMetadataMap() == null) { return Address.NON_ADDRESS; } return Optional.ofNullable((Long) getMetadataMap() .get(LogUnitMetadataType.GLOBAL_ADDRESS)).orElse(Address.NON_ADDRESS); }

Target:
I don't think you need this, Its either empyt, or it doesn't have the key.
Source:
protected List<ILogData> getNextEntries(T context, long maxGlobal, Function<ILogData, Boolean> contextCheckFn) { final List<ILogData> dataList = new ArrayList<>(); ILogData thisData; while ((thisData = streamReadWithCheck(()->getNextEntry(context, maxGlobal), 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; }

Target:
This getNextEntries is the super class impl, it has a overridden impl. You need to change that.
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. return read(context.getGlobalPointer()); }

Target:
Why you are not checking compaction mark here?
Source:
public void gcUnsafe() { while (garbageSendingDeque.size() < SENDING_QUEUE_CAPACITY) { List<SMRGarbageEntry> garbageEntries = new ArrayList<>(); int drainedNum = garbageReceivingQueue.drainTo(garbageEntries, BATCH_SIZE); GarbageBatch garbageBatch = new GarbageBatch(compressGarbage(garbageEntries)); garbageSendingDeque.offer(garbageBatch); if (drainedNum < BATCH_SIZE) { break; } } log.debug("GarbageInformer: Drains sending queue"); sendGarbage(); }

Target:
Check drainedNum == 0 right after this line? Otherwise your batch could be zero.
Source:
protected List<Object> identifyRemoveGarbage(Object locator, K key) { List<Object> garbage = new ArrayList<>(); // TODO(Xin): Distinguish put and remove in the future garbage.addAll(locatorStore.addUnsafe(key, (SMRRecordLocator) locator)); return garbage; }

Target:
Same here, you can use `List<Object> garbage = new ArrayList<>(locatorStore.addUnsafe(key, (SMRRecordLocator) locator));`
Source:
protected List<Object> identifyClearGarbage(Object locator) { List<Object> garbage = new ArrayList<>(); garbage.addAll(locatorStore.clearUnsafe()); return garbage; }

Target:
Make it consistent with other two.
Source:
public List<Object> identifyPutGarbage(Object locator, K key, V value) { List<Object> garbage = new ArrayList<>(); garbage.addAll(locatorStore.addUnsafe(key, (SMRRecordLocator) locator)); return garbage; }

Target:
Make them consistent with CorfuTable.
Source:
protected void clearIndex() { indexSpec.clear(); secondaryIndexes.clear(); indexGenerationFailed = true; }

Target:
should `indexGenerationFailed` be volatile or AtomicBoolean?
Source:
static ILogData getLogData(CorfuRuntime runtime, boolean loadInCache, long address) { if (loadInCache) { return runtime.getAddressSpaceView().read(address); } else { return runtime.getAddressSpaceView().fetch(address, false); } }

Target:
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.
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() .read(Collections.singleton(address)) .get(address); } catch (TrimmedException te) { processTrimmedException(te); throw te; } }

Target:
Why is this behavior changed? It used to be NOT waitForWrite, but now it waits instead. Is that true?
Source:
public CorfuGuidGenerator(CorfuRuntime rt) { runtime = rt; try { distributedCounter = (SMRMap<Integer, Long>) (rt.getObjectsView().build() .setType(SMRMap.class) .setStreamName(GUID_STREAM_NAME) .open()); } catch (Exception e) { log.error("Failed to initialize CorfuGuidGenerator", e); throw e; } }

Target:
Why try/catch? just let it fail. Also, the cast is not necessary.
Source:
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().toString()); mainMap = mapImpl; }

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

Target:
Please combine and remove the nested if.
Source:
public LogMetadata() { this.globalTail = Address.NON_ADDRESS; this.streamTails = new HashMap(); this.streamsAddressSpaceMap = new HashMap(); }

Target:
`this.streamsAddressSpaceMap = new HashMap<>();`
Source:
public Long getLogTail() { return logMetadata.getGlobalTail(); }

Target:
please use `long`
Source:
private void prefixTrim(CorfuPayloadMsg<TrimRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { try { TrimRequest req = msg.getPayload(); batchWriter.prefixTrim(new Token(msg.getEpoch(), req.getAddress().getSequence())); r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); } catch (TrimmedException ex) { r.sendResponse(ctx, msg, CorfuMsgType.ERROR_TRIMMED.msg()); } }

Target:
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.
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(); } cache.invalidateUpTo(trimMark); r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); }

Target:
If the trim mark doesn't change why do you still iterate the cache ?
Source:
public long getStartingAddress() { if (startingAddress.get() == Address.NON_ADDRESS) { long dbStartingAddress = Optional.ofNullable(dataStore.get(STARTING_ADDRESS_RECORD)).orElse(ZERO_ADDRESS); startingAddress.set(dbStartingAddress); } return startingAddress.get(); }

Target:
can you change this name, let's not use db, maybe use trimMark.
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) .holeFillTimeout(holeFillTimeout) .build()); // Default number of times to read before hole filling to 0 // (most aggressive, to surface concurrency issues). runtime.getParameters().setHoleFillRetry(0); }

Target:
Should this change be moved to #1763 ?
Source:
public void gc(long trimMark) { Timer.Context vloGcDuration = VloMetricsHelper.getVloGcContext(); 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(); } } }

Target:
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.
Source:
private void handleEviction(long address, ILogData entry, RemovalCause cause) { log.trace("Eviction[{}]: {}", address, cause); streamLog.release(address, (LogData) entry); }

Target:
What if the implementations of release changes from no op?
Source:
private long getCompactionCounter() { final Timer compactionTimer = metricRegistry.timer(StreamLogCompaction.STREAM_COMPACT_METRIC); return compactionTimer == null ? 0 : compactionTimer.getCount(); }

Target:
As I know, if timer doesn't exists it will be created, so no need to check for null
Source:
public synchronized void sealServerWithEpoch(long epoch) { batchWriter.waitForSealComplete(epoch); log.info("LogUnit sealServerWithEpoch: sealed and flushed with epoch {}", epoch); }

Target:
why is this synchronized ?
Source:
public List<AbstractServer> getServers() { return ImmutableList.copyOf(servers); }

Target:
What's the point of returning immutable copies, why not just make the class field immutable and return that?
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(); if (!layout.getAllServersNodes().contains(getLocalEndpoint())) { return false; } return true; }

Target:
it should be getAllServers or getAllServerNodes
Source:
public CorfuTable() { this(IndexRegistry.empty()); log.warn("CorfuTable: Creating a table without secondary indexes! Secondary index lookup" + " will fail."); }

Target:
I suggest that this message is change to "table created with the following indexes" as opposed to printing the warning.
Source:
private void consumeOperationQueue() { // Assign a worker for each thread in the pool for (int i = 0; i < numThreads; i++) { workers.execute(() -> { while (!operationQueueLock && !operationQueue.isEmpty()) { try { Operation op = operationQueue.take(); op.execute(); } catch (Exception e) { log.error("Operation failed with", e); } } }); } }

Target:
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.
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(); } getRuntime.cleanup(CorfuRuntime::shutdown); log.info("Orchestrator shutting down."); }

Target:
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.
Source:
private void updateLocalMetrics() { suppressExceptions(() -> { // 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)); }); }

Target:
i do not think wrapping should be here . It should be at scheduling level. The problem is that scheduler is finicky.
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); log.debug("sendRequest: requested to add on orchestrator {}:{}", nodeForWorkflow, managementClient.getRouter().getHost(), managementClient.getRouter().getPort()); return resp.getWorkflowId(); }

Target:
You can leave this as info. It is helpful for debugging.
Source:
public boolean hasNext() { if (currInd < maxInd) { return true; } else { return false; } }

Target:
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.
Source:
public synchronized <T> void put(Class<T> tclass, String prefix, String key, T value) { String json = JsonUtils.parser.toJson(value, tclass); T tmpVal = JsonUtils.parser.fromJson(json, tclass); DataStoreKey dsk = new DataStoreKey(getKey(prefix, key), tclass); cache.put(dsk, tmpVal); }

Target:
Is this parse to and from JSON to clone the object?
Source:
public AddNodeWorkflow(Request request) { this.id = UUID.randomUUID(); this.request = (AddNodeRequest) request; actions = Arrays.asList(new BootstrapNode(), new AddNodeToLayout(), new StateTransfer(), new MergeSegments()); }

Target:
Can you use a ImmutableList (Guava)?
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); } else { resp = new QueryResponse(false); } r.sendResponse(ctx, msg, CorfuMsgType.ORCHESTRATOR_RESPONSE .payloadMsg(new OrchestratorResponse(resp ))); }

Target:
does the queryResponse not return any status of the workflow or it's actions ?
Source:
public Layout getCurrentLayout() { while (true) { try { return runtime.layout.get(); } catch (SystemUnavailableException sue) { 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); } } } }

Target:
This shouldn't be necessary, the error will not be caught by the exception catch block below
Source:
public Collection<Object> getByIndex(@Nonnull F indexFunction, I index) { return indexFunction.getProjectionFunction() .generateProjection(index, indexMap .getOrDefault(indexFunction, ImmutableMultimap.of()).get(index)); }

Target:
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.
Source:
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; }

Target:
if !indexFunctions.isEmpty()
Source:
public TrimmedException() { address = -1; }

Target:
Can you use the Address.NON_EXIST constant?
Source:
public ServerNotReadyException() { super("Server not ready to accept messages."); }

Target:
Exception already indicates that?
Source:
public synchronized long getTailSegment() { Long tailSegment = dataStore.get(Long.class, PREFIX_TAIL_SEGMENT, KEY_TAIL_SEGMENT); return tailSegment == null ? 0 : tailSegment; }

Target:
why do you need this synchronized. I remember the datastore gave you that. I might be wrong.
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() || !layout.getClusterId().equals(latestLayout.getClusterId())) { latestLayout = layout; // Persisting this new updated layout setCurrentLayout(latestLayout); } }

Target:
Change the layout any time cluster ID doesn't match?...That looks very permissive.
Source:
public <R> R access(ICorfuSMRAccess<R, T> accessMethod, Object[] conflictObject) { R value; boolean isEnabled = MetricsUtils.isMetricsCollectionEnabled(); Timer.Context context = MetricsUtils.getConditionalContext(isEnabled, timerAccess); try { value = accessInner(accessMethod, conflictObject, isEnabled); } finally { MetricsUtils.stopConditionalContext(isEnabled, context); } return value; }

Target:
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.
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); return context == null ? cf : cf.thenApply(x -> { context.stop(); return x; }); }

Target:
same. I'll stop repeating.
Source:
public synchronized 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())); }

Target:
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.
Source:
public synchronized long obtainSnapshotTimestamp() { 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; } }

Target:
should be marked final
Source:
public void shutdown() { // Shutting the fault detector. isShutdown = true; 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); } }

Target:
What is the significance of this 5 second wait? Why not just do shutdownNow?
Source:
public PropertyEntry getShallowestProperty() { if ( !propertyEntries.isEmpty() ) { return first( propertyEntries ); } return null; }

Target:
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) ;` `}`
Source:
public String toString() { return element.getSimpleName().toString() + "( . )"; }

Target:
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.
Source:
public Set<Type> getImportTypes() { Set<Type> types = new HashSet<Type>(); for ( MapperReference mapperReference : mapperReferences ) { types.add( mapperReference.getType() ); } for ( Annotation annotation : annotations ) { types.add( annotation.getType() ); } return types; }

Target:
Use `mapperReference#getImportTypes()` instead
Source:
AbstractAccessor(T element) { this.element = element; if (element.getEnclosingElement().getKind() == ElementKind.CLASS) { 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; } }

Target:
This means that we can't build interfaces with builders right?
Source:
public boolean isAbstract() { return typeElement != null && typeElement.getKind().isClass() && typeElement.getModifiers().contains( Modifier.ABSTRACT ); }

Target:
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".
Source:
public boolean isAbstract() { return (declaringMapper != null && declaringMapper.getTypeElement().getKind().isInterface()) || executable.getModifiers().contains( Modifier.ABSTRACT ); }

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

Target:
I'm wondering whether we should create sub-types instead of using the booleans.
Source:
private String getName(Type sourceType, Type targetType) { String fromName = getName( sourceType ); String toName = getName( targetType ); String with = nullValueMappingStrategy != null ? "WithNvms" + camelizeEnumConstant( nullValueMappingStrategy ) : ""; return Strings.decapitalize( fromName + "To" + toName + with ); }

Target:
"camelize"... that's flowerly... 🐫 👍
Source:
private boolean isExecutableType(TypeMirror accessorType) { return accessorType.getKind() == TypeKind.EXECUTABLE && accessorType instanceof ExecutableType; }

Target:
I reckon the && is not needed, right?
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 { LEVEL.set( level.intValue() - 1 ); } }

Target:
not needed unboxing
Source:
public Set<Type> getImportTypes() { Set<Type> imported = new HashSet<Type>( getAssignment().getImportTypes().size() + 1 ); imported.addAll( getAssignment().getImportTypes() ); imported.add( enumType ); return imported; }

Target:
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 )`.
Source:
public ExecutableType getMethodType(TypeElement includingType, ExecutableElement method) { DeclaredType asType = (DeclaredType) replaceTypeElementIfNecessary( elementUtils, includingType ).asType(); TypeMirror asMemberOf = SpecificCompilerWorkarounds.asMemberOf( asType, method, typeUtils, elementUtils ); ExecutableType methodType = asMemberOf.accept( new ExecutableTypeRetrievalVisitor(), null ); return methodType; }

Target:
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.
Source:
protected List<Annotation> getTypeAnnotations(Mapper mapper) { if ( mapper.getDecorator() == null ) { return Arrays.asList( singleton(), named() ); } else { return Collections.singletonList( namedDelegate( mapper ) ); } }

Target:
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.
Source:
public void analyze() { for ( Node node : nodes.values() ) { depthFirstSearch( node ); } }

Target:
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?
Source:
private List<String> getCurrentCycle(Node start) { List<String> cycle = new ArrayList<String>(); boolean inCycle = false; for ( Node n : currentPath ) { if ( n.getName().equals( start.getName() ) ) { inCycle = true; } if ( inCycle ) { cycle.add( n.getName() ); } } return cycle; }

Target:
you could even check for `n == start`, right? Or use `n.equals( start )`, as your equals-implementation in Node checks for reference equality first.
Source:
public PlayerNetworkComponent getNetwork() { return getExact(PlayerNetworkComponent.class); }

Target:
This kills the ability for Vanilla to extend PlayerNetworkComponent.
Source:
public boolean execute(BlockComponentHolder component) { try { for (Component c : component.values()) { if (c.canTick()) { c.tick(dt); } } } catch (Exception e) { Spout.getLogger().log(Level.SEVERE, "Unhandled exception while ticking block component", e); } return true; }

Target:
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.
Source:
public synchronized DateFormat get() { DateFormat dateFormat = threadMap.get(Thread.currentThread()); if (dateFormat == null) { dateFormat = (DateFormat) templateFormat.clone(); threadMap.put(Thread.currentThread(), dateFormat); } return dateFormat; }

Target:
@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; } `
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()); assertEquals("Automatically determined optimal packaging for safe and secure delivery", packaging.getDescription()); assertEquals("packaging", packaging.getObject()); }

Target:
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.
Source:
public List<NodePropertyDescriptor> getNodePropertiesDescriptors() { DescriptorExtensionList<NodeProperty<?>, NodePropertyDescriptor> nodePropertyDescriptors = NodeProperty.all(); return nodePropertyDescriptors.stream() .filter(npd -> npd.isApplicable(vSphereCloudSlave.class)) .collect(Collectors.toList()); }

Target:
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)
Source:
public boolean filter(@CheckForNull Object context, @NonNull Descriptor descriptor) { return !(descriptor instanceof vSphereCloudProvisionedSlave.DescriptorImpl); }

Target:
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.
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. Jenkins.get().addNode(slave); return slave; }

Target:
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.
Source:
public Map<String, Object> getData() { return Collections.unmodifiableMap(this.data); }

Target:
unneeded
Source:
public String toString() { return "Script " + this.name + " from version " + from + " to " + to; }

Target:
`from` and `to` can be null. ```suggestion return "Script " + this.name + (from != null ? " from version " + from : "") + (to != null ? " to " + to : ""); ```
Source:
public void addExtraData(String variable, Object variableValue) { if (this.data == null) { this.data = new HashMap<String, Object>(); } this.data.put(variable, variableValue); }

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

Target:
<String, Object> not needed.
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++) { TimeUnit.MILLISECONDS.sleep(1000); ProcessInstance pi = kieSession.startProcess(processId); if (pi != null) { piList.add(pi); } } return piList; }

Target:
Reduce sleep time (probably a few milliseconds is enough)
Source:
public void dispose() { if (ksession != null) { abortProcessInstances(ksession); ksession.dispose(); ksession = null; } if (ksession2 != null) { ksession2.dispose(); ksession2 = null; } }

Target:
Same, it can be removed
Source:
private int executeWithParameters(Map<String, Object> params, Query query) { applyMetaQueryParameters(params, query); query.getParameters() .stream() .filter(e -> params.containsKey(e.getName())) .forEach(p -> query.setParameter(p.getName(), params.get(p.getName()))); return query.executeUpdate(); }

Target:
I believe `applyMetaQueryParameters` already handles this. Or is this because of something else?
Source:
public void setup() { // disable auto init of timers since ejb timer service supports persistence of timers System.setProperty("org.jbpm.rm.init.timer", "false"); logger.info("Using local cache for EJB timers: {}", (USE_LOCAL_CACHE ? "true" : "false")); }

Target:
Why do we need to use conditional expression and the print true or false, isn’t it enough to directly priny USELOCALCACHE?
Source:
static void cleanupSingletonSessionId() { File tempDir = new File(System.getProperty("java.io.tmpdir")); if (tempDir.exists()) { String[] jbpmSerFiles = tempDir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith("-jbpmSessionId.ser"); } }); for (String file : jbpmSerFiles) { new File(tempDir, file).delete(); } } }

Target:
This should be on one line.
Source:
public void cleanup() { cleanupSingletonSessionId(); if (units != null && !units.isEmpty()) { for (DeploymentUnit unit : units) { try { deploymentService.undeploy(unit); } catch (Exception e) { // do nothing in case of some failed tests to avoid next test to fail as well logger.error("---------------------------" + e.getLocalizedMessage()); logger.error("--do nothing in case of some failed tests to avoid next test to fail as well-------------------------" + unit.getIdentifier()); } } units.clear(); } close(); }

Target:
Do we need this logging? Maybe we can at least decrease the logging level to debug so it doesn't pollute logs when tests are run.
Source:
public Object getData(String name) { Object result = this.data.get(name); if (result == null && name != null && name.equalsIgnoreCase("caseid")) { result = getCaseId(); } return result; }

Target:
I believe we can change ``` name != null && name.equalsIgnoreCase("caseid") ``` for ``` "caseid".equalsIgnoreCase(name) ```. Will be much easier to read.
Source:
public void triggerAdHocFragment(String caseId, String stageId, String fragmentName, Object data) throws CaseNotFoundException { authorizationManager.checkAuthorization(caseId); ProcessInstanceDesc pi = verifyCaseIdExists(caseId); triggerAdHocFragment(pi.getId(), stageId, fragmentName, data); }

Target:
This call is missing in the second method.
Source:
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { try { manager.completeWorkItem(workItem.getId(), null); } catch(Throwable cause) { handleException(cause); manager.abortWorkItem(workItem.getId()); } }

Target:
I don't think we should call abortWorkItem here as the work item most likely won't be there as it failed to execute.
Source:
public static List<String> getAuthenticatedUserRoles(IdentityProvider identityProvider) { List<String> roles = identityProvider != null ? identityProvider.getRoles() : new ArrayList<>(); if (roles == null || roles.isEmpty()) { roles = new ArrayList<>(); roles.add(""); } return roles; }

Target:
Seems to be a compilation issue here, new ArrayList<>() should be new ArrayList\<String\>()
Source:
public Object getContentObject() { throw new UnsupportedOperationException("Not implemented for JPA"); }

Target:
wha would it take to implement this for JPA? bit uncomfortable to have new methods only for particular type ...
Source:
public Collection<CaseInstance> getCaseInstances(QueryContext queryContext) { Map<String, Object> params = new HashMap<String, Object>(); params.put("statuses", statuses); applyQueryContext(params, queryContext); applyDeploymentFilter(params); List<CaseInstance> processInstances = commandService.execute(new QueryNameCommand<List<CaseInstance>>("getCaseInstances", params)); return processInstances; }

Target:
The method below could be reused passing the default statuses, avoiding code dup.
Source:
public static NotificationListenerManager get() { if (INSTANCE == null) { INSTANCE = new NotificationListenerManager(); } return INSTANCE; }

Target:
If you want to lazy-load the manager instance, would it be okay to use the [lazy holder idiom](https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom)? I believe that the above code is a minor race condition.
Source:
public void afterCompletion(int status) { try { manager.disposeRuntimeEngine(runtime); } catch (Throwable e) { logger.warn("Could not dispose runtime engine", e); } }

Target:
Please do -- in general, there are very few (if any) dispose or cleanup operations that should be warn. We only use warn for operations that directly prevent or impair normal operation. If you can push -f (force) a fix to the pull request, that would be great! Thanks.
Source:
private static void sendWithRest(MessageChannel channel) { IntStream.range(1, 10).forEach(i -> { channel.send(MessageBuilder.withPayload(createEvent()).build()); }); }

Target:
Don't see reason to use `Streams` here. The simple `for (int i = 0; i < 10; i++)` should be enough.
Source:
public String getVersionChanges(String versionStr) { Map<String, String> depends = new HashMap<>(); JSONObject version = versions.getJSONObject(versionStr); if (version.containsKey("changes")) { return version.getString("changes"); } return null; }

Target:
What's this variable for?
Source:
public GHDiscussion wrapUp(GHTeam team) throws IOException { this.root = team.root; this.organization = team.getOrganization(); this.team = team; return this; }

Target:
```suggestion public GHDiscussion wrapUp(GHTeam team) throws IOException { this.organization = team.getOrganization(); ```
Source:
public void shouldPreferClientDestPortWhenInitialized() { HttpRequestMessageImpl message = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", new HttpQueryParams(), new Headers(), "192.168.0.2", "https", 7002, "localhost", new InetSocketAddress("api.netflix.com", 443)); assertEquals(message.getClientDestinationPort(), 443); }

Target:
Line wrapping is odd here. Either fill all the lines all the way, or put one arg per line. This is for consistency.
Source:
public void stop() { LOG.debug("Shutting down Zuul."); serverGroup.stop(); // remove the shutdown hook that was added when the proxy was started, since it has now been stopped try { Runtime.getRuntime().removeShutdownHook(jvmShutdownHook); } catch (IllegalStateException e) { // This can happen if the VM is already shutting down LOG.debug("Failed to remove shutdown hook", e); } LOG.debug("Completed zuul shutdown."); }

Target:
Why change these to debug?
Source:
private SslContext getClientSslContext() throws SSLException { return SslContextBuilder .forClient() .sslProvider(BaseSslContextFactory.chooseSslProvider()) .startTls(true) .build(); }

Target:
Can you add `.protocols()` explicitly here. There's a `getProtocols()` method in `BaseSslContextFactory`. Should probably be `TLSv1.2`. I think maybe a cleaner solution is to subclass that class and create a `ClientSslContextFactory` that holds this logic. You can initialize it in the constructor of this class and just call this method in the init block.
Source:
public void setSerial(int port) { this.localPort = port; serial = EMULATOR_SERIAL_PREFIX + port; }

Target:
I believe this line is incorrect and should be removed
Source:
public void stop() { if (serverThread == null) { throw new IllegalStateException("Server is not running"); } serverThread.interrupt(); TrafficCounter.shutdown(); }

Target:
Should this be called in `finally` above instead? The `TrafficCounter` is set up in the `ServerInitializer`.