auphong2707/dl4se-code-review-dataset huggingface dataset:
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()), START command.hasFlag(Flag.PUT_FOR_STATE_TRANSFER)); END } 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); } } } I think you could have removed the `RecipientGenerator` completely and passed the key directly.

Target:
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, 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); } } }
Source:
public Object visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable { if (isStoreAsBinary()) { for (Object key : command.getKeys()) { START if (getMightGoRemote(ctx, key, command)) END checkMarshallable(key); } } return super.visitGetAllCommand(ctx, command); } 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.

Target:
public Object visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable { for (Object key : command.getKeys()) { if (isStoreAsBinary() || getMightGoRemote(ctx, key, command)) checkMarshallable(key); } return super.visitGetAllCommand(ctx, command); }
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) { START if (entry == null && activator != null) { END //entry does not exists before. we need to activate it. activator.activate(key); } return newEntry; } }); } `activator` is never `null`

Target:
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) { //entry does not exists before. we need to activate it. activator.activate(key); } return newEntry; } }); }
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) { START if (!future.isDone()) { END future.attachListener(internalListener); } else { internalListener.futureDone(future); } } } Race condition?

Target:
public CompositeNotifyingFuture(List<NotifyingFuture<T>> futures) { this.futures = futures; this.remaining = new CountDownLatch(futures.size()); InternalListener internalListener = new InternalListener(); for (NotifyingFuture<T> future : futures) { future.attachListener(internalListener); } }
Source:
public void removeScript(String name) { START if (!getScriptCache().containsKey(name)) { END throw log.noNamedScript(name); } else { getScriptCache().remove(name); } } Seems we can do this via a null check of the return value of remove ? else this isn't atomic.

Target:
public void removeScript(String name) { if (getScriptCache().remove(name) == null) { throw log.noNamedScript(name); } }
Source:
START protected void fetchClusterWideStatsIfNeeded() { END 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(); } } } 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.

Target:
protected synchronized 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(); } } }
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) { START log.interruptedWaitingForCoordinator(e); END } } } finally { viewUpdateLock.unlock(); } } not sure if it is the best exception. IMO, you should throw the `InterruptedException` instead of ignoring it.

Target:
public void waitForView(int viewId) throws InterruptedException { if (channel == null) return; log.tracef("Waiting on view %d being accepted", viewId); viewUpdateLock.lock(); try { while (channel != null && this.getViewId() < viewId) { viewUpdateCondition.await(); } } finally { viewUpdateLock.unlock(); } }
Source:
START public void setAvailability(AvailabilityMode availability) { END if (partitionHandlingManager != null) { try { localTopologyManager.setCacheAvailability(getName(), availability); } catch (Exception e) { throw new CacheException(e); } } } `@Override` is missing

Target:
public void setAvailability(AvailabilityMode availability) { if (localTopologyManager != null) { try { localTopologyManager.setCacheAvailability(getName(), availability); } catch (Exception e) { throw new CacheException(e); } } }
Source:
public BackupPushStateStatusCommand() { START super(0); END } The parameter needs to be 1 since the backup model node is one level below the cache

Target:
public BackupPushStateStatusCommand() { super(1); }
Source:
START public C convert(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) { END return filterAndConvert(key, oldValue, oldMetadata, newValue, newMetadata, eventType); } would be useful to mark these methods as final?

Target:
public final C convert(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) { return filterAndConvert(key, oldValue, oldMetadata, newValue, newMetadata, eventType); }
Source:
START public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { END // 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); } I'm guessing the clear command deletes everything in the cache anyway.

Target:
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); for (String fileName : serializationContext.getFileDescriptors().keySet()) { serializationContext.unregisterProtoFile(fileName); } return invokeNextInterceptor(ctx, command); }
Source:
public String getPendingViewAsString() { CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); START return (!(cacheTopology != null && cacheTopology.getPendingCH() != null)) ? "N/A" END : cacheTopology.getPendingCH().getMembers().toString(); } Reverse the operands to avoid negation maybe? Would look nicer.

Target:
public String getPendingViewAsString() { CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); return (cacheTopology != null && cacheTopology.getPendingCH() != null) ? cacheTopology.getPendingCH().getMembers().toString() : "N/A"; }
Source:
START public synchronized Iterable<Cache<K,V>> iterateAllCaches() { END return caches; } Insufficient synchronization. Maybe should return a copy of the internal list.

Target:
public synchronized Iterable<Cache<K, V>> iterateAllCaches() { return new ArrayList<Cache<K, V>>(caches); }
Source:
START public boolean isMissingData() { END return getCacheTopology() != null && getCacheTopology().isDegradedMode(); } I really prefer "isDegradedMode" to be used everywhere for consistency, even in non-public API

Target:
public boolean isMissingData() { return getCacheTopology() != null && getCacheTopology().isMissingData(); }
Source:
protected ConfigurationBuilder clusterConfig() { START ConfigurationBuilder builder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC, false); END builder.jmxStatistics().enable(); return hotRodCacheConfiguration(builder); } Seems this can be simplified to just call super.clusterConfig and then invoke jmxStatistics.enable().

Target:
protected ConfigurationBuilder clusterConfig() { ConfigurationBuilder builder = super.clusterConfig(); builder.jmxStatistics().enable(); return hotRodCacheConfiguration(builder); }
Source:
START public void testByteArrayStrippedLockTx() throws InterruptedException, TimeoutException, ExecutionException { END doTest(CacheName.STRIPPED_LOCK_TX); } Nitpicking: should just declare Exception

Target:
public void testByteArrayStrippedLockTx() throws Exception { doTest(CacheName.STRIPPED_LOCK_TX); }
Source:
protected void killSpawnedThreads() { List<Runnable> runnables = defaultExecutorService.shutdownNow(); START log.errorf("There were runnables %s left uncompleted in test %s", runnables, getClass().getSimpleName()); END for (TrackingThreadFactory factory : requestedThreadFactories) { checkFactoryForLeaks(factory); } } We should only log this if runnables is not empty.

Target:
protected void killSpawnedThreads() { List<Runnable> runnables = defaultExecutorService.shutdownNow(); if (!runnables.isEmpty()) { log.errorf("There were runnables %s left uncompleted in test %s", runnables, getClass().getSimpleName()); } for (TrackingThreadFactory factory : requestedThreadFactories) { checkFactoryForLeaks(factory); } }
Source:
private SocketAddress nextServer(Set<SocketAddress> failedServers) { SocketAddress server; START if (balancer instanceof FailoverRequestBalancingStrategy) { END server = ((FailoverRequestBalancingStrategy) balancer).nextServer(failedServers); } else { server = balancer.nextServer(); } return server; } instead of checking this every time, can't you wrap in `start()` the `RequestBalancingStrategy` in `FailoverRequestBalancingStrategy` and delegate the new method?

Target:
private SocketAddress nextServer(Set<SocketAddress> failedServers) { return balancer.nextServer(failedServers); }
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('@'); START realmUser = realmSep < 0 ? new RealmUser(authorizationId) : new RealmUser(authorizationId.substring(realmSep+1), authorizationId.substring(0, realmSep)); END } don't you need to handle the case where `realmSep == 0`?

Target:
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)); }
Source:
public EmbeddedQuery(AdvancedCache<?, ?> cache, String jpaQuery, Class<? extends Matcher> matcherImplClass) { START retriever = cache.getComponentRegistry().getComponent(EntryRetriever.class); END this.jpaQuery = jpaQuery; this.matcherImplClass = matcherImplClass; } 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 } ```

Target:
public EmbeddedQuery(AdvancedCache<?, ?> cache, String jpaQuery, Class<? extends Matcher> matcherImplClass) { this.cache = cache; this.jpaQuery = jpaQuery; this.matcherImplClass = matcherImplClass; }
Source:
protected Configuration getRemoteCacheManagerConfig(String login, String password) { ConfigurationBuilder config = getDefaultConfigBuilder(); config.security().authentication().serverName(TEST_SERVER_NAME); START config.security().authentication().saslMechanism(getTestedMech()); END config.security().authentication().callbackHandler(new LoginHandler(login, password, TEST_REALM)); config.security().authentication().enable(); return config.build(); } why not fluent ?

Target:
protected Configuration getRemoteCacheManagerConfig(String login, String password) { ConfigurationBuilder config = getDefaultConfigBuilder(); config.security().authentication() .serverName(TEST_SERVER_NAME) .saslMechanism(getTestedMech()) .callbackHandler(new LoginHandler(login, password, TEST_REALM)) .enable(); return config.build(); }
Source:
public void stop() { if (isStarted()) { transportFactory.destroy(); asyncExecutorService.shutdownNow(); START listenerNotifier.stop(); END } started = false; } Shouldn't this happen before you shut down the asyncExecutorService to which it is bound ?

Target:
public void stop() { if (isStarted()) { listenerNotifier.stop(); transportFactory.destroy(); asyncExecutorService.shutdownNow(); } started = false; }
Source:
public void removeClientListener(byte[] listenerId) { START EventDispatcher dispatcher = clientListeners.get(listenerId); END dispatcher.transport.release(); // force shutting it clientListeners.remove(listenerId); if (log.isTraceEnabled()) log.tracef("Remove client listener with id %s", Util.printArray(listenerId)); } Can this just be remove instead, so it doesn't need to be called 2 lines down?

Target:
public void removeClientListener(byte[] listenerId) { EventDispatcher dispatcher = clientListeners.remove(listenerId); dispatcher.transport.release(); // force shutting it if (log.isTraceEnabled()) log.tracef("Remove client listener with id %s", Util.printArray(listenerId)); }
Source:
private void writeNamedFactory(Transport transport, String factoryName, byte[][] params) { if (factoryName.isEmpty()) { START transport.writeByte((short) 0); END } else { transport.writeString(factoryName); if (params != null) { transport.writeByte((short) params.length); for (byte[] param : params) transport.writeArray(param); } else { transport.writeByte((short) 0); } } } 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?

Target:
private void writeNamedFactory(Transport transport, String factoryName, byte[][] params) { transport.writeString(factoryName); if (!factoryName.isEmpty()) { // A named factory was written, how many parameters? if (params != null) { transport.writeByte((short) params.length); for (byte[] param : params) transport.writeArray(param); } else { transport.writeByte((short) 0); } } }
Source:
START public DefaultCommandMatcher(Class<? extends ReplicableCommand> commandClass) { END this(commandClass, null, null, null, MATCH_ANY_COUNT); } 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 :)

Target:
public DefaultCommandMatcher(Class<? extends ReplicableCommand> commandClass) { this(commandClass, null, null, null); }
Source:
public int hashCode() { START int result = interval != null ? interval.hashCode() : 0; END result = 31 * result + (condition != null ? condition.hashCode() : 0); return result; } 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?

Target:
public int hashCode() { return interval != null ? interval.hashCode() : condition.hashCode(); }
Source:
public String toString() { START return "OwnableReentrantStripedLockContainer{" + "sharedLocks=" + (Arrays.asList(sharedLocks)) + '}'; END } Redundant parenthesis. Also do you know why this isn't just calling Arrays.toString ?

Target:
public String toString() { return "OwnableReentrantStripedLockContainer{" + "sharedLocks=" + Arrays.toString(sharedLocks) + '}'; }
Source:
public static void checkPermission(Subject subject, int subjectMask, AuthorizationPermission perm) { if ((subjectMask & perm.getMask()) != perm.getMask()) { if (System.getSecurityManager() == null) { START throw log.unauthorizedAccess(subject == null ? "null" : subject.toString(), perm.toString()); END } else { System.getSecurityManager().checkPermission(perm.getSecurityPermission()); } } } `String.valueOf()` would avoid checking for null by our code :P

Target:
public static void checkPermission(Subject subject, int subjectMask, AuthorizationPermission perm) { if ((subjectMask & perm.getMask()) != perm.getMask()) { if (System.getSecurityManager() == null) { throw log.unauthorizedAccess(String.valueOf(subject), perm.toString()); } else { System.getSecurityManager().checkPermission(perm.getSecurityPermission()); } } }
Source:
public static ClassLoader[] getClassLoaders(ClassLoader appClassLoader) { return new ClassLoader[] { appClassLoader, // User defined classes START new OsgiClassLoader(), END Util.class.getClassLoader(), // Infinispan classes (not always on TCCL [modular env]) ClassLoader.getSystemClassLoader() // Used when load time instrumentation is in effect }; } 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.

Target:
public static ClassLoader[] getClassLoaders(ClassLoader appClassLoader) { return new ClassLoader[] { appClassLoader, // User defined classes OsgiClassLoader.getInstance(), // OSGi bundle context needs to be on top of TCCL, system CL, etc. Util.class.getClassLoader(), // Infinispan classes (not always on TCCL [modular env]) ClassLoader.getSystemClassLoader() // Used when load time instrumentation is in effect }; }
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); START if (rCache == null) { END throw new IllegalArgumentException("Result cache " + resultsCache + " is not defined on this node"); } executeHelper(resultsCache); } I don't think this is possible, if the cache is not defined it will be created with the default configuration.

Target:
public void execute(String resultsCache) throws CacheException { if (resultsCache == null || resultsCache.isEmpty()) { throw new IllegalArgumentException("Results cache can not be " + resultsCache); } executeHelper(resultsCache); }
Source:
public InternalCacheEntry<K, V> remove(Object k) { START InternalCacheEntry e = entries.remove(k); END return e == null || (e.canExpire() && e.isExpired(timeService.wallClockTime())) ? null : e; } missing `<K,V>`

Target:
public InternalCacheEntry<K, V> remove(Object k) { InternalCacheEntry<K, V> e = entries.remove(k); return e == null || (e.canExpire() && e.isExpired(timeService.wallClockTime())) ? null : e; }
Source:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(getCacheMode(), true); START builder.clustering().stateTransfer().chunkSize(128); END createClusteredCaches(4, cacheName(), builder); } 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?

Target:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(getCacheMode(), true); builder.clustering().stateTransfer().chunkSize(2); createClusteredCaches(4, cacheName(), builder); }
Source:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(getCacheMode(), true); START builder.clustering().stateTransfer().chunkSize(32); END createClusteredCaches(2, cacheName(), builder); } Why 32 and not 128?

Target:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(getCacheMode(), true); builder.clustering().stateTransfer().chunkSize(2); createClusteredCaches(2, cacheName(), builder); }
Source:
public String getProperty(String key) { START return this.properties.get(key).toString(); END } `return String.valueOf(this.properties.get(key))` perhaps? to protect from null...

Target:
public String getProperty(String key) { return String.valueOf(this.properties.get(key)); }
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)); START if (initialPriority != null) thread.setPriority(initialPriority); END thread.setDaemon(true); return thread; } `initialPriority` is always different from null

Target:
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)); thread.setPriority(initialPriority); thread.setDaemon(true); return thread; }
Source:
public org.infinispan.transaction.TransactionMode getMode() { START switch (this) { END case NON_XA: case NON_DURABLE_XA: case FULL_XA: return org.infinispan.transaction.TransactionMode.TRANSACTIONAL; default: return org.infinispan.transaction.TransactionMode.NON_TRANSACTIONAL; } } could be smaller: `return this == NONE ? NON_TRANSACTIONAL : TRANSACTIONAL`

Target:
public org.infinispan.transaction.TransactionMode getMode() { return this == NONE ? org.infinispan.transaction.TransactionMode.NON_TRANSACTIONAL : org.infinispan.transaction.TransactionMode.TRANSACTIONAL; }
Source:
public int compareTo(FileEntry fe) { int diff = size - fe.size; START return (diff != 0) ? diff : (int) (offset - fe.offset); END } 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`.

Target:
public int compareTo(FileEntry fe) { // We compare the size first, as the entries in the free list must be sorted by size int diff = size - fe.size; if (diff != 0) return diff; return (offset < fe.offset) ? -1 : ((offset == fe.offset) ? 0 : 1); }
Source:
public void clearCache() { START cacheManager.getCache().clear(); END TestingUtil.recursiveFileRemove(indexDir); } it should check `cacheManager != null`

Target:
public void clearCache() { if (cacheManager != null) { cacheManager.getCache().clear(); } TestingUtil.recursiveFileRemove(indexDir); }
Source:
public BackupReceiverImpl(Cache cache) { this.cache = cache; //TODO can we have a local cache? START this.local = cache.getCacheConfiguration().clustering().cacheMode() == CacheMode.LOCAL; END siteUpdater = new BackupCacheUpdater(cache, remote2localTx); } 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.

Target:
public BackupReceiverImpl(Cache cache) { this.cache = cache; siteUpdater = new BackupCacheUpdater(cache, remote2localTx); }
Source:
public Object[] getParameters() { switch (control) { case START_SEND: case FINISH_SEND: case CANCEL_SEND: return new Object[]{control.toByte(), siteName}; } START return new Object[]{control.toByte()}; END } 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.

Target:
public Object[] getParameters() { return new Object[]{control, siteName}; }
Source:
private byte[] readClasspathResource(String c) throws IOException { InputStream is = getClass().getResourceAsStream(c); try { return Util.readStream(is); } finally { START is.close(); END } } here we should guard against null is

Target:
private byte[] readClasspathResource(String c) throws IOException { InputStream is = getClass().getResourceAsStream(c); try { return Util.readStream(is); } finally { if (is != null) { is.close(); } } }
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); START replaceComponent(cache.getCacheManager(), InboundInvocationHandler.class, handler, true); END return handler; } The lines above don't configure the mock, they are needed because CommandAwareRpcDispatcher is not a proper component.

Target:
private ControllerInboundInvocationHandler injectControllerInboundInvocationHandler(Cache cache) { ControllerInboundInvocationHandler handler = new ControllerInboundInvocationHandler( extractComponent(cache, InboundInvocationHandler.class)); replaceComponent(cache.getCacheManager(), InboundInvocationHandler.class, handler, true); JGroupsTransport t = (JGroupsTransport) extractComponent(cache, Transport.class); CommandAwareRpcDispatcher card = t.getCommandAwareRpcDispatcher(); replaceField(handler, "inboundInvocationHandler", card, CommandAwareRpcDispatcher.class); return handler; }
Source:
public Builder<?> read(Role template) { permissions.clear(); START for(CachePermission perm : template.getPermissions()) { END permissions.add(perm); } return this; } We could just use Set.addAll method instead.

Target:
public Builder<?> read(Role template) { permissions.clear(); permissions.addAll(template.getPermissions()); return this; }
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. START fe.waitUnlocked(); END // 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()); } } 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.

Target:
private void free(FileEntry fe) throws IOException { if (fe != null) { // 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()); } }
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); START System.out.print("Using " + cacheId + ": " + cache +"\t"); END return withFlags; } This System.out should probably be in the caller, not here. Btw, isnt's logging preferred to System.out, even in tests?

Target:
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); return withFlags; }
Source:
START V put(final K key, final V value) { END final V returnValue = clusterRegistry.put(scope, key, value); localCacheInsert(key, value); return returnValue; } Do we ever use the returned value? Even the put in the cluster registry should use IGNORE_RETURN_VALUES.

Target:
void put(final K key, final V value) { clusterRegistry.put(scope, key, value); localCacheInsert(key, value); }
Source:
public InvocationContext createSingleKeyNonTxInvocationContext() { START InvocationContext ctx = new SingleKeyNonTxInvocationContext(true, keyEq); END return ctx; } you don't need the variable. you can inline

Target:
public InvocationContext createSingleKeyNonTxInvocationContext() { return new SingleKeyNonTxInvocationContext(true, keyEq); }
Source:
private TestObjectStreamMarshaller marshaller() { START if (marshaller == null) { END marshaller = new TestObjectStreamMarshaller(); } return marshaller; } Is there a reason this class is doing this through lazy initialization instead of a BeforeMethod/BeforeTest like the other classes?

Target:
private TestObjectStreamMarshaller marshaller() { return marshaller; }
Source:
START public org.infinispan.configuration.cache.Configuration greetingCache() { END return new ConfigurationBuilder() .eviction().strategy(EvictionStrategy.LRU).maxEntries(4) .build(); } I don't wanna be too "noisy" but why the full class name in the methods on this class?

Target:
public Configuration greetingCache() { return new ConfigurationBuilder() .eviction().strategy(EvictionStrategy.LRU).maxEntries(4) .build(); }
Source:
START public static Metadata extractMetadata(Metadata metadata) { END Metadata toCheck = metadata; while (toCheck != null) { if (toCheck instanceof InternalMetadataImpl) { toCheck = ((InternalMetadataImpl) toCheck).actual(); } else { break; } } return toCheck; } Why public? If nowhere else used, I'd leave it as private.

Target:
private static Metadata extractMetadata(Metadata metadata) { Metadata toCheck = metadata; while (toCheck != null) { if (toCheck instanceof InternalMetadataImpl) { toCheck = ((InternalMetadataImpl) toCheck).actual(); } else { break; } } return toCheck; }
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. START !ctx.isOriginLocal() && !ctx.getAffectedKeys().isEmpty(); END } 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?

Target:
private boolean shouldFlushL1(TxInvocationContext ctx) { return !ctx.getAffectedKeys().isEmpty(); }
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(); START remoteCommandsExecutor.checkForReadyTasks(); END } } 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...

Target:
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(); } }
Source:
START Class getRootType() { END return rootType; } just to be sure that it is ok... it's normal these methods to be package protected instead of public? `getRootType`, `getStartOffset`, (and others)

Target:
protected Class getRootType() { return rootType; }
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()))) { START getLog().tracef("Sending additional invalidation for requestors if necessary."); END // 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; } I would guard all the `tracef` invocation in an `if (... isTraceLogEnabled())`

Target:
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()))) { if (trace) { log.trace("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; }
Source:
public int compareTo(Object o) { START if (!(o instanceof FileEntry)) END 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; } doing the cast directly would have the same result but would be a bit faster :-) FileEntry fe = (FileEntry) o;

Target:
public int compareTo(Object o) { FileEntry fe = (FileEntry) o; if (this == fe) return 0; int diff = size - fe.size; return (diff != 0) ? diff : offset > fe.offset ? 1 : -1; }
Source:
public void testGetOnlyQueriesCacheOnOwners() throws CacheLoaderException { START prepareClearTest(); END // 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)); } Why is this needed?

Target:
public void testGetOnlyQueriesCacheOnOwners() throws CacheLoaderException { // 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)); }
Source:
public IncrementableEntryVersion increment(IncrementableEntryVersion initialVersion) { START if (initialVersion == NonExistingVersion.INSTANCE) { END 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()); } nicer to have a method IncrementableEntryVersion.incrementVersion()::IncrementableEntryVersion to take care of this. Would drop the not-so-nice instanceof.

Target:
public IncrementableEntryVersion increment(IncrementableEntryVersion initialVersion) { if (initialVersion instanceof NumericVersion) { NumericVersion old = (NumericVersion) initialVersion; long counter = old.getVersion() + 1; return createNumericVersion(counter); } throw log.unexpectedInitialVersion(initialVersion.getClass().getName()); }
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()) { START txTable.remoteTransactionCommitted(command.getGlobalTransaction(), false); END } else { txTable.remoteTransactionPrepared(command.getGlobalTransaction()); } } return result; } I believe that is `true` instead of `false`

Target:
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(), true); } else { txTable.remoteTransactionPrepared(command.getGlobalTransaction()); } } return result; }
Source:
public void setExpiryQueueSize(int expiryQueueSize) { testImmutability("expiryQueueSize"); START setProperty(location, "location", properties); END this.expiryQueueSize = expiryQueueSize; } Looks like it should be s/location/expiryQueueSize/

Target:
public void setExpiryQueueSize(int expiryQueueSize) { testImmutability("expiryQueueSize"); setProperty(String.valueOf(expiryQueueSize), "expiryQueueSize", properties); this.expiryQueueSize = 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 START if (enabled && passivationEnabled && !shouldSkipCacheLoader(command)) { END 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; } @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.

Target:
public Object visitKeySetCommand(InvocationContext ctx, KeySetCommand command) throws Throwable { Object keys = super.visitKeySetCommand(ctx, command); if (enabled && !shouldSkipCacheLoader(command)) { Set<Object> union = new HashSet<Object>((Set<Object>)keys); // Exclude the keys in memory as we don't want to deserialize those again union.addAll(loader.loadAllKeys(union)); return Collections.unmodifiableSet(union); } return keys; }
Source:
public void stop() { // Clear class cache marshallableTypeHints.clear(); // Clear thread local START marshallerTL.remove(); END } 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

Target:
public void stop() { // Clear class cache marshallableTypeHints.clear(); }
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(); START assertEquals(cache(0).get(k), "v"); END } Order of expected and actual values is wrong.

Target:
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("v", cache(0).get(k)); }
Source:
private void assertValue(int nodeIndex, Object key, Object expectedValue) { START InternalCacheEntry entry = cache(nodeIndex).getAdvancedCache().getDataContainer().get(key); END assertEquals(expectedValue, entry != null ? entry.getValue() : null); } Why go to the data container to check this? Why not call `cache.get()`?

Target:
private void assertValue(int nodeIndex, Object key, Object expectedValue) { assertEquals(expectedValue, cache(nodeIndex).get(key)); }
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)) { START throw new RejectedExecutionException("Queue is full"); END } } checkForUnblockTasks(); if (log.isTraceEnabled()) { log.tracef("Added a new task: %s task(s) are waiting", blockedTasks.size()); } } AFAICT your queue is unlimited, so you shouldn't need to throw a RejectedExecutionException.

Target:
public final void execute(BlockingRunnable runnable) { if (shutdown) { throw new RejectedExecutionException("Executor Service is already shutdown"); } if (runnable.isReady()) { doExecute(runnable); } else { blockedTasks.offer(runnable); } if (log.isTraceEnabled()) { log.tracef("Added a new task: %s task(s) are waiting", blockedTasks.size()); } }
Source:
protected Set<byte[]> executeOperation(Transport transport) { HeaderParams params = writeHeader(transport, BULK_GET_KEYS_REQUEST); transport.flush(); START System.out.println("hello"); END 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; } This line should be removed

Target:
protected Set<byte[]> executeOperation(Transport transport) { HeaderParams params = writeHeader(transport, BULK_GET_KEYS_REQUEST); transport.flush(); readHeaderAndValidate(transport, params); Set<byte[]> result = new HashSet<byte[]>(); while ( transport.readByte() == 1) { //there's more! result.add(transport.readArray()); } return result; }
Source:
protected <T> T getOrCreateComponent(Class<T> componentClass, String name) { START return getOrCreateComponent(componentClass, name, true); END } I don't think it matters, but strictly speaking if you're passing a name explicitly I think the `isFQCN` parameter should be `false`.

Target:
protected <T> T getOrCreateComponent(Class<T> componentClass, String name) { return getOrCreateComponent(componentClass, name, false); }
Source:
public EmbeddedCacheManager getDefaultCacheManager(@OverrideDefault Instance<EmbeddedCacheManager> providedDefaultCacheManager, @Default Configuration defaultConfiguration) { if (!providedDefaultCacheManager.isUnsatisfied()) { if (log.isTraceEnabled()) { START log.tracef("Default cache manager overridden by '%s'", providedDefaultCacheManager); END } return providedDefaultCacheManager.get(); } return new DefaultCacheManager(defaultConfiguration); } 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.

Target:
public EmbeddedCacheManager getDefaultCacheManager(@OverrideDefault Instance<EmbeddedCacheManager> providedDefaultCacheManager, @Default Configuration defaultConfiguration) { if (!providedDefaultCacheManager.isUnsatisfied()) { log.tracef("Default cache manager overridden by '%s'", providedDefaultCacheManager); return providedDefaultCacheManager.get(); } return new DefaultCacheManager(defaultConfiguration); }
Source:
private void stop() { notifier.removeListener(cleanupService); cm.removeListener(cleanupService); START cleanupService.stop(); END shutDownGracefully(); } Missing cm.removeListener(this)?

Target:
private void stop() { notifier.removeListener(cleanupService); cm.removeListener(cleanupService); cm.removeListener(this); shutDownGracefully(); }
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); START return gotPermission; END } this method can either return true or throw an exception, never return false. A boolean return is not required.

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