auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void notifySync(Queue<CountDownLatch> latches) { if (latches == null) { return; } while (true) { CountDownLatch latch = latches.poll(); if (latch == null) { break; } latch.countDown(); } }

Target:
This was the method I was talking about where concurrent writes for the same key, value would notify more than 1 caller at the same time. I wonder if it is okay if we just notify 1 latch and return?
Source:
public void close() throws Exception { }

Target:
This shouldn't declare throws Exception.
Source:
public V replace(K key, V value) { V v = delegate.replace(key, value); if (v != null) { stats.incrementCacheHits(); } else { stats.incrementCacheMisses(); } stats.incrementCachePuts(); return v; }

Target:
It seems we aren't being very inconsistent with cache hits/misses on writes. The put methods don't increment these counters, is that correct? Is there some sort of unit test for the stats counters? I worry there may be overlap between this class and explicit increments in the JCache class itself. I would think this class would handle all the stats itself, or is there something else I am missing?
Source:
public void register(Member member) throws Exception { Search.getFullTextEntityManager(em).persist(member); initNewMember(); }

Target:
'em.persist(member);' should be enough, you only need to wrap the EntityManager when needing to access methods which are not exposed on the JPA API.
Source:
private boolean updateCacheTopology(String cacheName, CacheTopology cacheTopology, Address sender, LocalCacheStatus cacheStatus) { // Block if there is a status request in progress // The caller should have already acquired the cacheStatus monitor synchronized (runningCaches) { if (!sender.equals(transport.getCoordinator())) { log.debugf("Ignoring topology %d from old coordinator %s", cacheTopology.getTopologyId(), sender); return false; } else { log.debugf("Updating local topology for cache %s: %s", cacheName, cacheTopology); cacheStatus.setCurrentTopology(cacheTopology); } } return true; }

Target:
is this change really needed?
Source:
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { if (command.hasFlag(Flag.PUT_FOR_EXTERNAL_READ)) { return handleNonTxWriteCommand(ctx, command); } try { return handleTxWriteCommand(ctx, command, new SingleKeyRecipientGenerator(command.getKey()), command.hasFlag(Flag.PUT_FOR_STATE_TRANSFER)); } finally { if (ctx.isOriginLocal()) { // If the state transfer interceptor has to retry the command, it should ignore the previous value. command.setValueMatcher(command.isSuccessful() ? ValueMatcher.MATCH_ALWAYS : ValueMatcher.MATCH_NEVER); } } }

Target:
I think you could have removed the `RecipientGenerator` completely and passed the key directly.
Source:
public Object visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable { if (isStoreAsBinary()) { for (Object key : command.getKeys()) { if (getMightGoRemote(ctx, key, command)) checkMarshallable(key); } } return super.visitGetAllCommand(ctx, command); }

Target:
The marshallable check should happen if storeIsBinary is enabled OR if the command might be replicated to another node. TBH I'm not sure why it is that way, the serialization should happen on the user thread in both cases (at least with async marshalling disabled), but AND is probably not ok.
Source:
public void putAndActivate(final InternalCacheEntry newEntry) { ((ConcurrentHashMapV8<Object, InternalCacheEntry>) entries) .compute(newEntry.getKey(), new ConcurrentHashMapV8.BiFun<Object, InternalCacheEntry, InternalCacheEntry>() { @Override public InternalCacheEntry apply(Object key, InternalCacheEntry entry) { if (entry == null && activator != null) { //entry does not exists before. we need to activate it. activator.activate(key); } return newEntry; } }); }

Target:
`activator` is never `null`
Source:
public CompositeNotifyingFuture(List<NotifyingFuture<T>> futures) { this.futures = futures; this.remaining = new CountDownLatch(futures.size()); InternalListener internalListener = new InternalListener(); for (NotifyingFuture<T> future : futures) { if (!future.isDone()) { future.attachListener(internalListener); } else { internalListener.futureDone(future); } } }

Target:
Race condition?
Source:
public void removeScript(String name) { if (!getScriptCache().containsKey(name)) { throw log.noNamedScript(name); } else { getScriptCache().remove(name); } }

Target:
Seems we can do this via a null check of the return value of remove ? else this isn't atomic.
Source:
protected void fetchClusterWideStatsIfNeeded() { if (launchNewDistTask()) { List<Future<Map<String, Number>>> responseList = Collections.emptyList(); try { responseList = des.submitEverywhere(new DistributedCacheStatsCallable()); updateFieldsFromResponseMap(responseList); } catch (Exception e) { log.warn("Could not execute cluster wide cache stats operation ", e); } finally { statsUpdateTimestamp = ts.time(); } } }

Target:
It seems that if this method is invoked by more than 1 thread you could have more than 1 cluster stats collection happening at the same time. Maybe we should synchronize this? This would also take care of the issue that all the variables read are not volatile since you could have partial updates seen due to memory model reordering operations.
Source:
public void waitForView(int viewId) { if (channel == null) return; log.tracef("Waiting on view %d being accepted", viewId); viewUpdateLock.lock(); try { while (channel != null && this.getViewId() < viewId) { try { viewUpdateCondition.await(); } catch (InterruptedException e) { log.interruptedWaitingForCoordinator(e); } } } finally { viewUpdateLock.unlock(); } }

Target:
not sure if it is the best exception. IMO, you should throw the `InterruptedException` instead of ignoring it.
Source:
public void setAvailability(AvailabilityMode availability) { if (partitionHandlingManager != null) { try { localTopologyManager.setCacheAvailability(getName(), availability); } catch (Exception e) { throw new CacheException(e); } } }

Target:
`@Override` is missing
Source:
public BackupPushStateStatusCommand() { super(0); }

Target:
The parameter needs to be 1 since the backup model node is one level below the cache
Source:
public C convert(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) { return filterAndConvert(key, oldValue, oldMetadata, newValue, newMetadata, eventType); }

Target:
would be useful to mark these methods as final?
Source:
public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { // lock .errors key VisitableCommand cmd = commandsFactory.buildLockControlCommand(ERRORS_KEY_SUFFIX, null, null); invoker.invoke(ctx, cmd); SerializationContext serializationContext = protobufMetadataManager.getSerializationContext(); for (String fileName : serializationContext.getFileDescriptors().keySet()) { serializationContext.unregisterProtoFile(fileName); } return invokeNextInterceptor(ctx, command); }

Target:
I'm guessing the clear command deletes everything in the cache anyway.
Source:
public String getPendingViewAsString() { CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); return (!(cacheTopology != null && cacheTopology.getPendingCH() != null)) ? "N/A" : cacheTopology.getPendingCH().getMembers().toString(); }

Target:
Reverse the operands to avoid negation maybe? Would look nicer.
Source:
public synchronized Iterable<Cache<K,V>> iterateAllCaches() { return caches; }

Target:
Insufficient synchronization. Maybe should return a copy of the internal list.
Source:
public boolean isMissingData() { return getCacheTopology() != null && getCacheTopology().isDegradedMode(); }

Target:
I really prefer "isDegradedMode" to be used everywhere for consistency, even in non-public API
Source:
protected ConfigurationBuilder clusterConfig() { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); builder.jmxStatistics().enable(); return hotRodCacheConfiguration(builder); }

Target:
Seems this can be simplified to just call super.clusterConfig and then invoke jmxStatistics.enable().
Source:
public void testByteArrayStrippedLockTx() throws InterruptedException, TimeoutException, ExecutionException { doTest(CacheName.STRIPPED_LOCK_TX); }

Target:
Nitpicking: should just declare Exception
Source:
protected void killSpawnedThreads() { List<Runnable> runnables = defaultExecutorService.shutdownNow(); log.errorf("There were runnables %s left uncompleted in test %s", runnables, getClass().getSimpleName()); for (TrackingThreadFactory factory : requestedThreadFactories) { checkFactoryForLeaks(factory); } }

Target:
We should only log this if runnables is not empty.
Source:
private SocketAddress nextServer(Set<SocketAddress> failedServers) { SocketAddress server; if (balancer instanceof FailoverRequestBalancingStrategy) { server = ((FailoverRequestBalancingStrategy) balancer).nextServer(failedServers); } else { server = balancer.nextServer(); } return server; }

Target:
instead of checking this every time, can't you wrap in `start()` the `RequestBalancingStrategy` in `FailoverRequestBalancingStrategy` and delegate the new method?
Source:
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { AuthorizeCallback acb = (AuthorizeCallback) callbacks[0]; String authenticationId = acb.getAuthenticationID(); String authorizationId = acb.getAuthorizationID(); acb.setAuthorized(authenticationId.equals(authorizationId)); int realmSep = authorizationId.indexOf('@'); realmUser = realmSep < 0 ? new RealmUser(authorizationId) : new RealmUser(authorizationId.substring(realmSep+1), authorizationId.substring(0, realmSep)); }

Target:
don't you need to handle the case where `realmSep == 0`?
Source:
public EmbeddedQuery(AdvancedCache<?, ?> cache, String jpaQuery, Class<? extends Matcher> matcherImplClass) { retriever = cache.getComponentRegistry().getComponent(EntryRetriever.class); this.jpaQuery = jpaQuery; this.matcherImplClass = matcherImplClass; }

Target:
I was instead planning on using the filterEntries method on the AdvancedCache. so in the list method it would be ``` try (CloseableIterable<Map.Entry<Object, Object>> myIterable = cache.getAdvancedCache().filterEntries(filter).converter(filter)) { for (Map.Entry<Object, Object> entry : myIterable) { .... } } catch (IOException e) { // exception ignored } ```
Source:
protected Configuration getRemoteCacheManagerConfig(String login, String password) { ConfigurationBuilder config = getDefaultConfigBuilder(); config.security().authentication().serverName(TEST_SERVER_NAME); config.security().authentication().saslMechanism(getTestedMech()); config.security().authentication().callbackHandler(new LoginHandler(login, password, TEST_REALM)); config.security().authentication().enable(); return config.build(); }

Target:
why not fluent ?
Source:
public void stop() { if (isStarted()) { transportFactory.destroy(); asyncExecutorService.shutdownNow(); listenerNotifier.stop(); } started = false; }

Target:
Shouldn't this happen before you shut down the asyncExecutorService to which it is bound ?
Source:
public void removeClientListener(byte[] listenerId) { EventDispatcher dispatcher = clientListeners.get(listenerId); dispatcher.transport.release(); // force shutting it clientListeners.remove(listenerId); if (log.isTraceEnabled()) log.tracef("Remove client listener with id %s", Util.printArray(listenerId)); }

Target:
Can this just be remove instead, so it doesn't need to be called 2 lines down?
Source:
private void writeNamedFactory(Transport transport, String factoryName, byte[][] params) { if (factoryName.isEmpty()) { transport.writeByte((short) 0); } else { transport.writeString(factoryName); if (params != null) { transport.writeByte((short) params.length); for (byte[] param : params) transport.writeArray(param); } else { transport.writeByte((short) 0); } } }

Target:
I am not as familiar with the serialization process in hotrod, but couldn't you just pass the string either way? The only error case is if it is null, right?
Source:
public DefaultCommandMatcher(Class<? extends ReplicableCommand> commandClass) { this(commandClass, null, null, null, MATCH_ANY_COUNT); }

Target:
I see you came back around on this. I think it is nice since then you know know what constraints there are based on the command type :)
Source:
public int hashCode() { int result = interval != null ? interval.hashCode() : 0; result = 31 * result + (condition != null ? condition.hashCode() : 0); return result; }

Target:
This is a small nitpick, but maybe you should do the same as you have with equals (only doing 1 based on conditional). Or you are thinking it would give better spread since an interval is always multiplied by 31 where as the condition is never multiplied?
Source:
public String toString() { return "OwnableReentrantStripedLockContainer{" + "sharedLocks=" + (Arrays.asList(sharedLocks)) + '}'; }

Target:
Redundant parenthesis. Also do you know why this isn't just calling Arrays.toString ?
Source:
public static void checkPermission(Subject subject, int subjectMask, AuthorizationPermission perm) { if ((subjectMask & perm.getMask()) != perm.getMask()) { if (System.getSecurityManager() == null) { throw log.unauthorizedAccess(subject == null ? "null" : subject.toString(), perm.toString()); } else { System.getSecurityManager().checkPermission(perm.getSecurityPermission()); } } }

Target:
`String.valueOf()` would avoid checking for null by our code :P
Source:
public static ClassLoader[] getClassLoaders(ClassLoader appClassLoader) { return new ClassLoader[] { appClassLoader, // User defined classes new OsgiClassLoader(), Util.class.getClassLoader(), // Infinispan classes (not always on TCCL [modular env]) ClassLoader.getSystemClassLoader() // Used when load time instrumentation is in effect }; }

Target:
I see there are bundles referenced. You'd have to check with an OSGI expert to see if having a singleton instance of this class with references to bundle instances could be problematic.
Source:
public void execute(String resultsCache) throws CacheException { if (resultsCache == null || resultsCache.isEmpty()) { throw new IllegalArgumentException("Results cache can not be " + resultsCache); } Cache<Object, Object> rCache = cache.getCacheManager().getCache(resultsCache); if (rCache == null) { throw new IllegalArgumentException("Result cache " + resultsCache + " is not defined on this node"); } executeHelper(resultsCache); }

Target:
I don't think this is possible, if the cache is not defined it will be created with the default configuration.
Source:
public InternalCacheEntry<K, V> remove(Object k) { InternalCacheEntry e = entries.remove(k); return e == null || (e.canExpire() && e.isExpired(timeService.wallClockTime())) ? null : e; }

Target:
missing `<K,V>`
Source:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(getCacheMode(), true); builder.clustering().stateTransfer().chunkSize(128); createClusteredCaches(4, cacheName(), builder); }

Target:
I originally set this to 2 to make sure that the intermediate values are split at least once during the test. Does that still happen with 128?
Source:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(getCacheMode(), true); builder.clustering().stateTransfer().chunkSize(32); createClusteredCaches(2, cacheName(), builder); }

Target:
Why 32 and not 128?
Source:
public String getProperty(String key) { return this.properties.get(key).toString(); }

Target:
`return String.valueOf(this.properties.get(key))` perhaps? to protect from null...
Source:
private Thread createThread(final Runnable target) { final ThreadNameInfo nameInfo = new ThreadNameInfo(globalThreadIndexSequence.getAndIncrement(), factoryThreadIndexSequence.getAndIncrement(), factoryIndex, node, component); Thread thread = new Thread(threadGroup, target); thread.setName(nameInfo.format(thread, threadNamePattern)); if (initialPriority != null) thread.setPriority(initialPriority); thread.setDaemon(true); return thread; }

Target:
`initialPriority` is always different from null
Source:
public org.infinispan.transaction.TransactionMode getMode() { switch (this) { case NON_XA: case NON_DURABLE_XA: case FULL_XA: return org.infinispan.transaction.TransactionMode.TRANSACTIONAL; default: return org.infinispan.transaction.TransactionMode.NON_TRANSACTIONAL; } }

Target:
could be smaller: `return this == NONE ? NON_TRANSACTIONAL : TRANSACTIONAL`
Source:
public int compareTo(FileEntry fe) { int diff = size - fe.size; return (diff != 0) ? diff : (int) (offset - fe.offset); }

Target:
this is bad IMO. if `offset >>> fe.offset` the diff may overflow the int (and return a negative int instead of a positive one). you should use `Long.valueOf(offset).compareTo(fe.offset)` another suggestion is to swap the order... first check the `offset` then the `size` since it is most likely the `offset` to be different than the `size`.
Source:
public void clearCache() { cacheManager.getCache().clear(); TestingUtil.recursiveFileRemove(indexDir); }

Target:
it should check `cacheManager != null`
Source:
public BackupReceiverImpl(Cache cache) { this.cache = cache; //TODO can we have a local cache? this.local = cache.getCacheConfiguration().clustering().cacheMode() == CacheMode.LOCAL; siteUpdater = new BackupCacheUpdater(cache, remote2localTx); }

Target:
I don't see any problem with prohibiting x-site backup to/from a LOCAL cache, but I'm not that familiar with x-site configuration and I don't know if it's possible to do that validation.
Source:
public Object[] getParameters() { switch (control) { case START_SEND: case FINISH_SEND: case CANCEL_SEND: return new Object[]{control.toByte(), siteName}; } return new Object[]{control.toByte()}; }

Target:
I think you're over-optimizing a bit here, XSiteStateTransferControlCommands should be **very** rare, so a simple `return new Object[]{control, siteName}` would have been fine.
Source:
private byte[] readClasspathResource(String c) throws IOException { InputStream is = getClass().getResourceAsStream(c); try { return Util.readStream(is); } finally { is.close(); } }

Target:
here we should guard against null is
Source:
private ControllerInboundInvocationHandler injectControllerInboundInvocationHandler(Cache cache) { ControllerInboundInvocationHandler handler = new ControllerInboundInvocationHandler( extractComponent(cache, InboundInvocationHandler.class)); JGroupsTransport t = (JGroupsTransport) extractComponent(cache, Transport.class); CommandAwareRpcDispatcher card = t.getCommandAwareRpcDispatcher(); replaceField(handler, "inboundInvocationHandler", card, CommandAwareRpcDispatcher.class); replaceComponent(cache.getCacheManager(), InboundInvocationHandler.class, handler, true); return handler; }

Target:
The lines above don't configure the mock, they are needed because CommandAwareRpcDispatcher is not a proper component.
Source:
public Builder<?> read(Role template) { permissions.clear(); for(CachePermission perm : template.getPermissions()) { permissions.add(perm); } return this; }

Target:
We could just use Set.addAll method instead.
Source:
private void free(FileEntry fe) throws IOException { if (fe != null) { // Entry could still be in use (in _load). So, wait till it releases it. fe.waitUnlocked(); // Invalidate entry on disk (by setting keyLen field to 0) // No need to wait for readers to unlock here, the FileEntry instance is not modified, // and allocate() won't return an entry as long as it has a reader. channel.write(ByteBuffer.wrap(ZERO_INT), fe.offset + KEYLEN_POS); if (!freeList.add(fe)) { throw new IllegalStateException(String.format("Trying to free an entry that was not allocated: %s", fe)); } if (trace) log.tracef("Deleted entry at %d:%d, there are now %d free entries", fe.offset, fe.size, freeList.size()); } }

Target:
This interleaving of events can't happen, because entries.put() implicitly synchronizes on the entries SynchronizedMap. I think I found the problem, though: in allocate(), you moved the processing of the found entry outside of the loop. But the `free` variable is always initialized with the last entry in the free list, regardless of whether it is locked or not, if there is at least one free entry bigger than the one we're looking for.
Source:
private Cache<String, Car> getWriteOnlyCache(int cacheId) { Cache<String, Car> cache = cache(cacheId); AdvancedCache<String,Car> advancedCache = cache.getAdvancedCache(); AdvancedCache<String, Car> withFlags = advancedCache.withFlags(Flag.IGNORE_RETURN_VALUES, Flag.SKIP_INDEX_CLEANUP); System.out.print("Using " + cacheId + ": " + cache +"\t"); return withFlags; }

Target:
This System.out should probably be in the caller, not here. Btw, isnt's logging preferred to System.out, even in tests?
Source:
V put(final K key, final V value) { final V returnValue = clusterRegistry.put(scope, key, value); localCacheInsert(key, value); return returnValue; }

Target:
Do we ever use the returned value? Even the put in the cluster registry should use IGNORE_RETURN_VALUES.
Source:
public InvocationContext createSingleKeyNonTxInvocationContext() { InvocationContext ctx = new SingleKeyNonTxInvocationContext(true, keyEq); return ctx; }

Target:
you don't need the variable. you can inline
Source:
private TestObjectStreamMarshaller marshaller() { if (marshaller == null) { marshaller = new TestObjectStreamMarshaller(); } return marshaller; }

Target:
Is there a reason this class is doing this through lazy initialization instead of a BeforeMethod/BeforeTest like the other classes?
Source:
public org.infinispan.configuration.cache.Configuration greetingCache() { return new ConfigurationBuilder() .eviction().strategy(EvictionStrategy.LRU).maxEntries(4) .build(); }

Target:
I don't wanna be too "noisy" but why the full class name in the methods on this class?
Source:
public static Metadata extractMetadata(Metadata metadata) { Metadata toCheck = metadata; while (toCheck != null) { if (toCheck instanceof InternalMetadataImpl) { toCheck = ((InternalMetadataImpl) toCheck).actual(); } else { break; } } return toCheck; }

Target:
Why public? If nowhere else used, I'd leave it as private.
Source:
private boolean shouldFlushL1(TxInvocationContext ctx) { return shouldInvokeRemoteTxCommand(ctx) || // We fall into this situation if we are a remote node, happen to be the primary data owner and have locked keys. // it is still our responsibility to invalidate L1 caches in the cluster. !ctx.isOriginLocal() && !ctx.getAffectedKeys().isEmpty(); }

Target:
I think it would be enough to check if affectedKeys is not empty, either on the originator or on the owner. After all, the invalidation will be done only if there are requestors for a certain key, and that will only happen on the owners. But that still sounds a bit expensive, couldn't we use the same L1WriteSynchronizer approach as for non-tx caches and invalidate only from the primary owner instead?
Source:
private void afterResponseSent(CacheRpcCommand command, Response resp) { if (command instanceof TotalOrderCommitCommand || command instanceof TotalOrderVersionedCommitCommand || command instanceof TotalOrderRollbackCommand || (command instanceof TotalOrderPrepareCommand && (((PrepareCommand) command).isOnePhaseCommit() || resp instanceof ExceptionResponse))) { totalOrderExecutorService.checkForReadyTasks(); remoteCommandsExecutor.checkForReadyTasks(); } }

Target:
I think that makes no sense to `checkForReadyTasks()` in the `remoteCommandsExecutor`. the `checkForReadyTasks()` must be invoked when the state changes and possible tasks would be unblocked (in your case, whenever you receive (or increase) the topology id). Also, the total order commands will not change that state...
Source:
Class getRootType() { return rootType; }

Target:
just to be sure that it is ok... it's normal these methods to be package protected instead of public? `getRootType`, `getStartOffset`, (and others)
Source:
public Object visitDataWriteCommand(InvocationContext ctx, DataWriteCommand command, boolean assumeOriginKeptEntryInL1) throws Throwable { Object returnValue = invokeNextInterceptor(ctx, command); Object key; if (shouldUpdateOnWriteCommand(command) && command.isSuccessful() && cdl.localNodeIsPrimaryOwner((key = command.getKey()))) { getLog().tracef("Sending additional invalidation for requestors if necessary."); // Send out a last attempt L1 invalidation in case if someone cached the L1 // value after they already received an invalidation l1Manager.flushCache(Collections.singleton(key), ctx.getOrigin(), assumeOriginKeptEntryInL1); } return returnValue; }

Target:
I would guard all the `tracef` invocation in an `if (... isTraceLogEnabled())`
Source:
public int compareTo(Object o) { if (!(o instanceof FileEntry)) throw new ClassCastException(); if (this == o) return 0; FileEntry fe = (FileEntry) o; int diff = size - fe.size; return (diff != 0) ? diff : offset > fe.offset ? 1 : -1; }

Target:
doing the cast directly would have the same result but would be a bit faster :-) FileEntry fe = (FileEntry) o;
Source:
public void testGetOnlyQueriesCacheOnOwners() throws CacheLoaderException { prepareClearTest(); // Make a key that own'ers is c1 and c2 final MagicKey k = new MagicKey("key1", c1, c2); final String v1 = "real-data"; final String v2 = "stale-data"; // Simulate c3 was by itself and someone wrote a value that is now stale CacheStore store = TestingUtil.extractComponent(c3, CacheLoaderManager.class).getCacheStore(); store.store(TestInternalCacheEntryFactory.create(k, v2)); c1.put(k, v1); assertEquals(v1, c3.get(k)); }

Target:
Why is this needed?
Source:
public IncrementableEntryVersion increment(IncrementableEntryVersion initialVersion) { if (initialVersion == NonExistingVersion.INSTANCE) { return generateNew(); } else if (initialVersion instanceof NumericVersion) { NumericVersion old = (NumericVersion) initialVersion; long counter = old.getVersion() + 1; return createNumericVersion(counter); } throw log.unexpectedInitialVersion(initialVersion.getClass().getName()); }

Target:
nicer to have a method IncrementableEntryVersion.incrementVersion()::IncrementableEntryVersion to take care of this. Would drop the not-so-nice instanceof.
Source:
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { //if it is remote and 2PC then first log the tx only after replying mods if (this.statisticsEnabled) prepares.incrementAndGet(); Object result = invokeNextInterceptorAndVerifyTransaction(ctx, command); if (!ctx.isOriginLocal()) { if (command.isOnePhaseCommit()) { txTable.remoteTransactionCommitted(command.getGlobalTransaction(), false); } else { txTable.remoteTransactionPrepared(command.getGlobalTransaction()); } } return result; }

Target:
I believe that is `true` instead of `false`
Source:
public void setExpiryQueueSize(int expiryQueueSize) { testImmutability("expiryQueueSize"); setProperty(location, "location", properties); this.expiryQueueSize = expiryQueueSize; }

Target:
Looks like it should be s/location/expiryQueueSize/
Source:
public Object visitKeySetCommand(InvocationContext ctx, KeySetCommand command) throws Throwable { Object keys = super.visitKeySetCommand(ctx, command); // TODO: this doesn't do write through to the back end store and currently doesn't even do write through to the // backend data container if (enabled && passivationEnabled && !shouldSkipCacheLoader(command)) { Set<Object> set = loader.loadAllKeys(Collections.emptySet()); Set<Object> union = new HashSet<Object>(set); union.addAll((Set<Object>)keys); return Collections.unmodifiableSet(union); } return keys; }

Target:
@wburns I don't think we handle correctly the scenario in which passivation is disabled. In this case the entries in memory are a subset of the entries on the disk, so I think we should rather use the store instead of the memory for these operations.
Source:
public void stop() { // Clear class cache marshallableTypeHints.clear(); // Clear thread local marshallerTL.remove(); }

Target:
I don't think this helps, see https://issues.jboss.org/browse/ISPN-2786?focusedCommentId=12773517&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-12773517
Source:
public void testRemoveSeenCorrectly2() throws Throwable { Object k = getKey(); cache(0).put(k, "v"); tm(0).begin(); cache(0).remove(k); assertNull(cache(0).get(k)); tm(0).rollback(); assertEquals(cache(0).get(k), "v"); }

Target:
Order of expected and actual values is wrong.
Source:
private void assertValue(int nodeIndex, Object key, Object expectedValue) { InternalCacheEntry entry = cache(nodeIndex).getAdvancedCache().getDataContainer().get(key); assertEquals(expectedValue, entry != null ? entry.getValue() : null); }

Target:
Why go to the data container to check this? Why not call `cache.get()`?
Source:
public final void execute(BlockingRunnable runnable) { if (shutdown) { throw new RejectedExecutionException("Executor Service is already shutdown"); } if (runnable.isReady()) { doExecute(runnable); } else { if (!blockedTasks.offer(runnable)) { throw new RejectedExecutionException("Queue is full"); } } checkForUnblockTasks(); if (log.isTraceEnabled()) { log.tracef("Added a new task: %s task(s) are waiting", blockedTasks.size()); } }

Target:
AFAICT your queue is unlimited, so you shouldn't need to throw a RejectedExecutionException.
Source:
protected Set<byte[]> executeOperation(Transport transport) { HeaderParams params = writeHeader(transport, BULK_GET_KEYS_REQUEST); transport.flush(); System.out.println("hello"); readHeaderAndValidate(transport, params); System.out.println("validated"); Set<byte[]> result = new HashSet<byte[]>(); while ( transport.readByte() == 1) { //there's more! result.add(transport.readArray()); } return result; }

Target:
This line should be removed
Source:
protected <T> T getOrCreateComponent(Class<T> componentClass, String name) { return getOrCreateComponent(componentClass, name, true); }

Target:
I don't think it matters, but strictly speaking if you're passing a name explicitly I think the `isFQCN` parameter should be `false`.
Source:
public EmbeddedCacheManager getDefaultCacheManager(@OverrideDefault Instance<EmbeddedCacheManager> providedDefaultCacheManager, @Default Configuration defaultConfiguration) { if (!providedDefaultCacheManager.isUnsatisfied()) { if (log.isTraceEnabled()) { log.tracef("Default cache manager overridden by '%s'", providedDefaultCacheManager); } return providedDefaultCacheManager.get(); } return new DefaultCacheManager(defaultConfiguration); }

Target:
since the two arguments are passed as-is (no string concatenation) the nice consequence of using these formatters is that you don't need the if (log.isTraceEnabled). Of course it's not an issue, but FYI, as it makes code more readable.
Source:
private void stop() { notifier.removeListener(cleanupService); cm.removeListener(cleanupService); cleanupService.stop(); shutDownGracefully(); }

Target:
Missing cm.removeListener(this)?
Source:
protected boolean getPermissionToJoin() throws Exception { boolean gotPermission; if (distributionManager.isJoinComplete()) { throw new IllegalStateException("Join on " + getMyAddress() + " cannot be complete without rehash to finishing"); } // 1. Get chOld from coord. chOld = retrieveOldConsistentHash(); gotPermission = true; // 2. new CH instance if (chOld.getCaches().contains(self)) chNew = chOld; else chNew = createConsistentHash(configuration, chOld.getCaches(), distributionManager.getTopologyInfo(), self); return gotPermission; }

Target:
this method can either return true or throw an exception, never return false. A boolean return is not required.
Source:
public SubversionSCMSource(String id, String remoteBase, String credentialsId, String includes, String excludes) { super(id); this.remoteBase = StringUtils.removeEnd(remoteBase, "/") + "/"; setCredentialsId(credentialsId); setIncludes(StringUtils.defaultIfEmpty(includes, DescriptorImpl.DEFAULT_INCLUDES)); setExcludes(StringUtils.defaultIfEmpty(excludes, DescriptorImpl.DEFAULT_EXCLUDES)); this.additionalCredentials = new ArrayList<AdditionalCredentials>(); }

Target:
Usage of this collection is ineffective if you do not plan to modify it on the flight. Use `Collections.emptyList()` instead in the code
Source:
public CredentialsSVNAuthenticationProviderImpl(Credentials credentials) { this.provider = new RemotableSVNAuthenticationBuilderProvider(credentials, Collections.<String, Credentials>emptyMap(), /* TODO */ TaskListener.NULL); }

Target:
Better to use the `this()` invocation of the constructor below
Source:
private static WebDriverElement createWebDriverElement(Hook hook, WebElement element, WebDriver driver) throws CandybeanException { try { if ("select".equals(element.getTagName())) { return new WebDriverSelector(hook, driver); } return new WebDriverElement(hook, 0, driver, element); } catch (CandybeanException e) { throw e; } }

Target:
Why do we even need the catch if all it does is re-throw exactly the same exception?
Source:
private static WebElement findElement(Hook hook, WebDriver driver) throws CandybeanException { try { return driver.findElement(getBy(hook)); } catch (NoSuchElementException e) { throw e; } catch (WebDriverException e) { throw e; } }

Target:
Since these catch blocks have the same body and we're using Java 7, let's user the multi-catch syntax: } catch(NoSuchElementException|WebDriverException e {
Source:
public static ExpectedCondition<WebDriverElement> present(final Hook hook) { return new ExpectedCondition<WebDriverElement>() { @Override public WebDriverElement apply(WebDriver driver) { try { WebElement element = findElement(hook, driver); return createWebDriverElement(hook, element, driver); } catch (CandybeanException e) { return null; } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of " + hook; } }; }

Target:
Let's use multi-catch here.
Source:
public static void first() throws Exception { String candybeanConfigStr = System.getProperty("candybean_config"); if (candybeanConfigStr == null) candybeanConfigStr = AbstractTest.CONFIG_DIR.getCanonicalPath() + File.separator + "candybean.config"; System.out.println("candybeanConfigPath: " + candybeanConfigStr); Configuration candybeanConfig = new Configuration(new File(Utils.adjustPath(candybeanConfigStr))); candybean = Candybean.getInstance(candybeanConfig); iface = candybean.getInterface(); iface.start(); }

Target:
The reason it was named CB was so it'd be short when statically referenced. But, either way -- no biggie...
Source:
public List<Player> getNonreadyPlayers() { List<Player> result = new LinkedList<>(); result.addAll(lobbyPlayers); result.removeAll(readyPlayers); result.sort(Comparator.comparing(Player:: getName)); return result; }

Target:
I'm not sure the sorting should be in `ArenaImpl`. The reason `getNonreadyPlayers()` returns a List rather than a Set is likely because of its original call site in the `notready` command, where it is fed to a utility method that stringifies a List. So it's probably past laziness more than anything :P I think it makes more sense to do the sorting at the caller site rather than in here. If nothing else, it reduces the blast radius of the pull request and keeps the changes "collected" in the signs/rendering code.
Source:
public RosActivity(String notificationTicker, String notificationTitle) { super(); rosActivityComponent = new RosActivityComponent(this, notificationTicker, notificationTitle, new RosActivityEventsHandler()); }

Target:
I don't think this is necessary.
Source:
public Vector3 toCameraFrame(int pixelX, int pixelY) { double centeredX = pixelX - viewport.getWidth() / 2.0d; double centeredY = viewport.getHeight() / 2.0d - pixelY; return getCameraToScreenTransform().invert().apply(new Vector3(centeredX, centeredY, 0)); }

Target:
can both be final.
Source:
public void jumpToFrame(GraphName frame) { synchronized (mutex) { this.frame = frame; double scale = cameraToRosTransform.getScale(); resetTransform(); cameraToRosTransform = cameraToRosTransform.scale(scale / cameraToRosTransform.getScale()); } }

Target:
final?
Source:
public static long crc32(String data) { if (data == null) { return -1; } try { // get bytes from string byte bytes[] = data.getBytes("UTF-8"); Checksum checksum = new CRC32(); // update the current checksum with the specified array of bytes checksum.update(bytes, 0, bytes.length); // get the current checksum value return checksum.getValue(); } catch (UnsupportedEncodingException e) { return -1; } }

Target:
Should we catch that exception here ? or pass it along ? I am sure there is a very thin chance this will happen. But in any case. Also, can we just do a default data.getBytes() if UTF-8 fails on UnsupportedEncodingException ?
Source:
private void mergeProperties(Properties properties, Map<String, String> configurationMap) { if (properties != null) { for (final String name : properties.stringPropertyNames()) if (!configurationMap.containsKey(name)) { configurationMap.put(name, properties.getProperty(name)); } } }

Target:
Please add braces surrounding the for loop block. Otherwise this is confusing to read.
Source:
public String getAccessToken() throws PayPalRESTException { if (accessToken == null) { accessToken = generateAccessToken(); } else if ((accessToken != null) && (expiresIn() <= 0)) { accessToken = generateAccessToken(); } return accessToken; }

Target:
Can we refactor both of this if else if into one condition ? ``` java if (!accessToken || (accessToken && expiresIn() <= 0)) { accessToken = generateAccessToken(); } ```
Source:
private double[] getPercentages(List<Double> tBreaks, List<Bucket> buckets, int nvalues, int numClasses) { Map<Double, Integer> values = new HashMap<>(); for (Bucket b : buckets) { values.put(b.getMin(), b.getCount()); } ClassPercentagesManager percentagesManager = new ClassPercentagesManager(); return percentagesManager.getPercentages(values, tBreaks, nvalues, numClasses); }

Target:
Both histogram based natural breaks and quantiles percentage calculation require counting portions of buckets in a given set of ranges, that do not necessarily match the buckets limits. So why are the two using two different methods to compute the results?
Source:
private Double getOverlappingPercentages(double cMin, double cMax, double bMin, double bMax) { if (cMin > bMax || cMax < bMin) { return 0.0; } double regionMin = Math.max(cMin, bMin); double regionMax = Math.min(cMax, bMax); double dividend = regionMax - regionMin; double divider = bMax - bMin; if (dividend == divider) return 1.0; else return dividend / divider; }

Target:
But why not check explicitly for zero? This is opaque, it seems like you're trying to optimize away a division.
Source:
public boolean getOnlyCreateReportWithDifferentName() { return this.onlyCreateReportWithDifferentName; }

Target:
This will need a null check done to make sure the default is returned if the field isn't set (i.e. is null). See `getEscapeUnderscores` for an example although obviously the default return will be different :)
Source:
public final Object getAbstractBuildOwner(Run build, Class targetClass) { return build instanceof AbstractBuild ? (AbstractBuild) build : null; }

Target:
It can/should be private (and remove `@Restricted(NoExternalUse.class)`).
Source:
protected static WebDriver getCurrentBrowser() { return b.getCurrentWebDriver(); }

Target:
Are you sure that "protected static" is ok? To me it doesn't make sense as you can't override static methods.
Source:
public Batch getNextEmptyBatch() throws InterruptedException { synchronized(availableBatches) { if (availableBatches.isEmpty()) { availableBatches.wait(); Integer batchIdx = availableBatches.pop(); return batches[batchIdx]; } Integer batchIdx = availableBatches.pop(); return batches[batchIdx]; } }

Target:
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait%28%29 synchronization error
Source:
public int read() throws IOException { streamPos++; return 0; }

Target:
Seems a bit harsh, I'm guessing the TIFF reader never does a single byte read call?
Source:
public static String printCommentTree(List<CommentTreeElement> cs) { String buffer = ""; for (CommentTreeElement c : cs) { buffer += printCommentTree(c, 0); } return buffer; }

Target:
can you use instead of string concatenation a StringBuilder?
Source:
public UserInfo about(String username) throws ActionFailedException { // Send GET request to get the account overview if(username == "[deleted]") throw new ActionFailedException("There is no information associated with the username [deleted]"); JSONObject object = (JSONObject) restClient.get(String.format(ApiEndpointUtils.USER_ABOUT, username), null).getResponseObject(); JSONObject data = (JSONObject) object.get("data"); // Init account info wrapper return data != null ? new UserInfo(data) : null; }

Target:
can you add curly brackets to the if statement? it good practice so you don't end up with weird bugs in the future
Source:
public FlairActions(RestClient restClient) { this.restClient = restClient; this.user = null; }

Target:
if you don't specify the **this.user = null**, it will be null when the class is instantianciated, so this line is redundant
Source:
public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); if (!player.hasPlayedBefore()) { for (Object map : kits.getKits().keySet()) { Kit kit = kits.getKits().get(map); if (CommandBook.inst().hasPermission(player, "commandbook.kits.onfirstlogin."+map)) { kit.distribute(player); } } } }

Target:
Do an EntrySet, iterating through Map.Entry<String, Kit>
Source:
protected boolean isTokenRequest(final HttpServletRequest request) { return CommonUtils.isNotBlank(CommonUtils.safeGetParameter(request, this.artifactParameterName, this.safeParameters)); }

Target:
this class is final so these should be private
Source:
protected boolean isBackChannelLogoutRequest(final HttpServletRequest request) { return "POST".equals(request.getMethod()) && !isMultipartRequest(request) && CommonUtils.isNotBlank(CommonUtils.safeGetParameter(request, this.logoutParameterName, this.safeParameters)); }

Target:
this should be private also
Source:
private String retrieveParameterValueFromServletContextConfiguration(final FilterConfig filterConfig, final String propertyName) { final String value2 = filterConfig.getServletContext().getInitParameter(propertyName); if (CommonUtils.isNotBlank(value2)) { logger.info("Property loaded from ServletContext.getInitParameter with value [{}]", propertyName, value2); return value2; } return null; }

Target:
This could be `value` instead of `value2` here...
Source:
public CifsTelnetConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper, true); ConnectionValidator.assertIsWindowsHost(os, CIFS_PROTOCOL, cifsConnectionType); ConnectionValidator.assertNotNewStyleWindowsDomain(username, CIFS_PROTOCOL, cifsConnectionType); // Make sure that we're properly cleaned up by setting the connected state. connected(); }

Target:
static imports
Source:
public CifsWinRmConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper, true); ConnectionValidator.assertIsWindowsHost(os, CIFS_PROTOCOL, cifsConnectionType); ConnectionValidator.assertNotOldStyleWindowsDomain(username, CIFS_PROTOCOL, cifsConnectionType); }

Target:
static imports
Source:
public CifsWinrsConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper, true); ConnectionValidator.assertIsWindowsHost(os, CIFS_PROTOCOL, cifsConnectionType); ConnectionValidator.assetNotThroughJumpstation(mapper, CIFS_PROTOCOL, cifsConnectionType); ConnectionValidator.assertNoSingleQuoteInPassword(password, CIFS_PROTOCOL, cifsConnectionType); this.options = options; }

Target:
static imports
Source:
public void connect() { connection = new WinrsConnection(options, mapper, workingDirectory); connection.connectToWinrsProxy(options); if (connection.getWinrsProxyConnection().getHostOperatingSystem() != WINDOWS) { connection.disconnectFromWinrsProxy(); throw new IllegalArgumentException(format("Cannot create a " + CIFS_PROTOCOL + ":%s connection with a winrs proxy that is not running Windows", cifsConnectionType.toString().toLowerCase())); } connected(); }

Target:
Why first the connect, then the check and disconnect?
Source:
private synchronized void drainQueueForRequests() { final PrefetchRecordsRetrieved recordsToDeliver = (PrefetchRecordsRetrieved) peekNextResult(); // If there is an event available to drain and if there is at least one demand, // then schedule it for delivery if (publisherSession.hasDemandToPublish() && canDispatchRecord(recordsToDeliver)) { subscriber.onNext(recordsToDeliver.prepareForPublish()); recordsToDeliver.dispatched(); lastEventDeliveryTime = Instant.now(); } }

Target:
let's update peekNextResult() to return PrefetchRecordsRetrieved type, so no need to typecast here.
Source:
LeaseCoordinator(ILeaseManager<T> leaseManager, String workerIdentifier, long leaseDurationMillis, long epsilonMillis, int maxLeasesForWorker, int maxLeasesToStealAtOneTime, int maxLeaseRenewerThreadCount, IMetricsFactory metricsFactory) { this(leaseManager, getDefaultLeaseSelector(), workerIdentifier, leaseDurationMillis, epsilonMillis, maxLeasesForWorker, maxLeasesToStealAtOneTime, maxLeaseRenewerThreadCount, metricsFactory); }

Target:
The `public` can't be removed. This class is a public class, this would be a breaking change.
Source:
@Override public synchronized Boolean isLeader(String workerId) { // if no leaders yet, synchronously get leaders. This will happen at first Shard Sync. if (executeConditionCheckWithReadLock(() -> CollectionUtils.isNullOrEmpty(leaders))) { electLeaders(); // start a scheduled executor that will periodically update leaders. // The first run will be after a minute. // We don't need jitter since it is scheduled with a fixed delay and time taken to scan leases // will be different at different times and on different hosts/workers. leaderElectionThreadPool.scheduleWithFixedDelay(this::electLeaders, ELECTION_INITIAL_DELAY_MILLIS, ELECTION_SCHEDULING_INTERVAL_MILLIS, TimeUnit.MILLISECONDS); } return executeConditionCheckWithReadLock(() -> isWorkerLeaderForShardSync(workerId)); }

Target:
Nit: could you make sure `@Override` is in the line above the method. And also could you make sure all annotations in the PR are in the line above.
Source:
public final void testExecutorStateEventWithCustomHandler() { ExecutorStateEvent event = new ExecutorStateEvent(executor, leaseCoordinator); event.accept(customHandler); assertTrue(wasCustomHandlerInvoked); wasCustomHandlerInvoked = false; }

Target:
Not sure why this statement is the last statement. It doesn't seem to do anything.
Source:
public ShardConsumer(RecordsPublisher recordsPublisher, ExecutorService executorService, ShardInfo shardInfo, Optional<Long> logWarningForTaskAfterMillis, ShardConsumerArgument shardConsumerArgument, TaskExecutionListener taskExecutionListener) { this(recordsPublisher, executorService, shardInfo, logWarningForTaskAfterMillis, shardConsumerArgument, taskExecutionListener, ConsumerStates.INITIAL_STATE, ShardConsumer.metricsWrappingFunction(shardConsumerArgument.metricsFactory()), 8); }

Target:
Is there a reason for changing the order for the chained constructor? If not could you add the new parameter to the end of the list.
Source:
private void callShutdownOnStrategy() { if (!getRecordsRetrievalStrategy.isShutdown()) { getRecordsRetrievalStrategy.shutdown(); } isShutdown = true; }

Target:
Where is this changed to true to trigger shutdown.
Source:
public NSDictionary searchTargetNSDict(NSDictionary rootDict, CoffeeName targetName) { final NSArray itemNSArray = (NSArray) (rootDict .objectForKey(ITEM_ARRAY)); NSDictionary resultDict = null; for (NSObject item : itemNSArray.getArray()) { final NSDictionary dict = (NSDictionary) item; final String itemName = NSDictionaryHelper.stringForKey(dict, CoffeeName.ITEM_NAME); if (!TextUtils.equals(targetName.getCoffeeName(), itemName)) { // mCoffeeNameと異なる場合は次へ continue; } resultDict = dict; } return resultDict; }

Target:
``` if (TextUtils.equals(targetName.getCoffeeName(), itemName)) { return dict; } ``` で良さそうな気がする！ TextUtilsってクラスは知らなかった！！便利そうだね。
Source:
public PrinterDto create(@RequestBody PrinterDto dto) throws Exception { Printer printer = Dtos.to(dto); return get(printerService.create(printer)); }

Target:
It looks like this should still only throw `IOException`?