auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Iterator<Journal.JournalEntry> getJournalEntryIterator() { List<Iterator<Journal.JournalEntry>> componentIters = StreamUtils .map(JournalEntryIterable::getJournalEntryIterator, mDBs.values()); return Iterators.concat(getDbIterator(), getDbInfoIterator(), Iterators.concat(componentIters.iterator())); }

Target:
why can't the `mDBs.values()` also add the `DBInfo` entries?
Source:
public int available() throws IOException { int available = in.available() + (int) (((FSDataInputStream) in).getPos() - mPos); return available > 0 ? available : 0; }

Target:
Could you explain the logic here?
Source:
public int read() throws IOException { byte[] buffer = new byte[1]; int bytesRead = ((FSDataInputStream) in).read(mPos, buffer, 0, buffer.length); if (bytesRead > 0) { mPos += bytesRead; return BufferUtils.byteToInt(buffer[0]); } Preconditions.checkArgument(bytesRead != 0, "Expected a non-zero value if end of stream has not been reached"); return bytesRead; }

Target:
Is it valid to hit EOS here and return `-1`?
Source:
protected BaseFileSystem(FileSystemContext fsContext) { mFsContext = fsContext; mBlockStore = AlluxioBlockStore.create(fsContext); mCloser.register(mFsContext); }

Target:
@apc999 This needs to be public or reflection will not work
Source:
static CacheEvictor create(AlluxioConfiguration conf) { return CommonUtils.createNewClassInstance( conf.getClass(PropertyKey.USER_CLIENT_CACHE_EVICTOR_CLASS), new Class[0], new Object[0]); }

Target:
I think you want `null` instead of empty arrays?
Source:
public void onPlanStatusChange(PlanInfo planInfo) { Status status = planInfo.getStatus(); if (status.equals(Status.COMPLETED)) { done(planInfo.getId()); } else if (status.equals(Status.CANCELED) || status.equals(Status.FAILED)) { stop(planInfo.getId(), status, planInfo.getErrorMessage()); } }

Target:
should this be `switch` statement?
Source:
public SshCommand(String hostname, String[] execString) { super(execString); mHostName = hostname; mCommand = new String[]{"bash", "-c", String.format("ssh %s %s %s", ShellUtils.COMMON_SSH_OPTS, hostname, String.join(" ", execString))}; }

Target:
Can we just use this for the `super` constructor? (and hopefully keep `mCommand` `final`)
Source:
public ScpCommand(String remoteHost, String fromFile, String toFile, boolean isDir) { super(new String[]{}); String template = "scp %s %s:%s localhost:%s"; if (isDir) { template = "scp -r %s %s:%s localhost:%s"; } // copy from hostname to local mCommand = new String[]{"bash", "-c", String.format(template, ShellUtils.COMMON_SSH_OPTS, remoteHost, fromFile, toFile) }; mHostName = remoteHost; }

Target:
Can we use this when calling the `super` constructor?
Source:
private HiveMetaStoreClient getHive() throws IOException { if (mHive != null) { return mHive; } mHive = newHiveClient(); return mHive; }

Target:
I think we are going to have to make this thread safe, by using a lock to protect changes to the cached client. Probably a RW lock, read to get the client, write to update it.
Source:
private void submit(long workerId, JobCommand.Builder command) { if (!mWorkerIdToPendingCommands.containsKey(workerId)) { mWorkerIdToPendingCommands.put(workerId, Lists.newArrayList()); } mWorkerIdToPendingCommands.get(workerId).add(command.build()); }

Target:
Is this already protected by a lock?
Source:
protected void beforeExecute(Thread t, Runnable r) { super.beforeExecute(t, r); mPauseLock.lock(); try { mNumPaused++; while (mIsPaused) { mUnpaused.await(); } mNumPaused--; } catch (InterruptedException e) { t.interrupt(); } finally { mPauseLock.unlock(); } }

Target:
does this not have to be in the `finally` block?
Source:
public boolean shutdown() { // Stop accepting new connections. mServer.shutdown(); // Close resources that potentially owns active streams. try { mCloser.close(); } catch (IOException e) { LOG.warn("Failed to close resources during shutdown.", e); // Do nothing. } // Force shutdown remaining calls. mServer.shutdownNow(); // Wait until server terminates. try { return mServer.awaitTermination(mServerShutdownTimeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return false; } }

Target:
This looks like a change of behavior - we used to give some time to the server threads to finish RPC calls before we interrupt them.
Source:
public JobWorkerHealth(alluxio.grpc.JobWorkerHealth jobWorkerHealth) { mWorkerId = jobWorkerHealth.getWorkerId(); mLoadAverage = Lists.newArrayList(jobWorkerHealth.getLoadAverageList()); mLastUpdated = jobWorkerHealth.getLastUpdated(); mHostname = jobWorkerHealth.getHostname(); }

Target:
What's the reason to copy the gRPC value into a new list?
Source:
public static void beforeClass() throws Exception { sLocalAlluxioJobCluster = new LocalAlluxioJobCluster(); sLocalAlluxioJobCluster.setProperty(PropertyKey.JOB_MASTER_WORKER_HEARTBEAT_INTERVAL, "25ms"); sLocalAlluxioJobCluster.start(); sFileSystem = sLocalAlluxioClusterResource.get().getClient(); }

Target:
we already do this in `before()`. Can we just keep it non-static and remove it from here?
Source:
public void asyncWriteWithPersistWaitTime() throws Exception { AlluxioURI filePath = new AlluxioURI(PathUtils.uniqPath()); createTwoBytesFile(mFileSystem, filePath, 2000); CommonUtils.sleepMs(500); IntegrationTestUtils .checkPersistStateAndWaitForPersist(sLocalAlluxioClusterResource, mFileSystem, filePath, 2); }

Target:
if we shorten all the intervals for the cluster, can we shorten this? Or, does the last line do the wait anyways? If so, does this line do anything?
Source:
public static CsvReader create(AlluxioURI uri) throws IOException { Path inputPath = new Path(uri.getScheme(), uri.getAuthority().toString(), uri.getPath()); Configuration conf = ReadWriterUtils.readNoCacheConf(); FileSystem fs = inputPath.getFileSystem(conf); return new CsvReader(fs, inputPath); }

Target:
Can we do `new CsvReader(inputPath)` and do the conf/fs creation in the constructor?
Source:
private void enforceResumeJournals() { try { mJournalSystem.resume(); } catch (IOException e) { ProcessUtils.fatalError(LOG, e, "Failed to resume journals."); } }

Target:
catch throwable instead?
Source:
public void suspend() throws IOException { try (LockResource stateLock = new LockResource(mStateLock)) { Preconditions.checkState(!mSuspended, "Already suspended"); LOG.info("Suspending state machine."); mSuspended = true; LOG.info("Suspended state machine at sequence: {}", mLastAppliedSequence); } }

Target:
The previous log message can be removed since there is trivial logic in between.
Source:
public void start(Boolean isLeader) throws IOException { super.start(isLeader); mTransformManager.startHeartbeat(getExecutorService(), mMasterContext.getUserState()); }

Target:
does this heartbeat need to be stopped somewhere?
Source:
public boolean processJournalEntry(Journal.JournalEntry entry) { if (entry.hasAttachDb()) { apply(entry.getAttachDb()); return true; } else if (entry.hasAddTable()) { Database db = mDBs.get(entry.getAddTable().getDbName()); return db.processJournalEntry(entry); } else if (entry.hasDetachDb()) { apply(entry.getDetachDb()); } return false; }

Target:
this method needs to return `true` if this journal entry has been handled.
Source:
public int run(CommandLine cl) throws AlluxioStatusException { String[] args = cl.getArgs(); String dbName = args[0]; String dbType = args[1]; Properties p = cl.getOptionProperties(OPTION_OPTION.getOpt()); mClient.attachDatabase(dbName, dbType, Maps.fromProperties(p)); System.out.println(String.format("Attached database %s (type: %s)", dbName, dbType)); return 0; }

Target:
I feel like this output isn't very helpful since we are just reprinting the user-specified options
Source:
public AlluxioURI reverseResolve(AlluxioURI ufspath) throws IOException, AlluxioException { checkUri(ufspath); return rpc(client -> { AlluxioURI path = client.reverseResolve(ufspath); LOG.debug("Reverse resolved to {}", ufspath.getPath(), path.getPath()); return path; }); }

Target:
I think you can remove this check. That checks for the alluxio scheme and authority.
Source:
public List<alluxio.grpc.catalog.Partition> readTable(String dbName, String tableName, Constraint constraint) throws IOException { Table table = getTable(dbName, tableName); List<Partition> partitions = table.getPartitions(); // TODO(david): implement partition pruning List<alluxio.grpc.catalog.Partition> returnList = partitions.stream().map(Partition::toProto).collect(Collectors.toList()); return returnList; }

Target:
Can we return this directly?
Source:
public boolean isRootListable() { try { return getObjectListingChunkForPath("", true) != null; } catch (Exception e) { LOG.debug("Unable to list root of bucket {}:", super.mUri.toString(), e.getMessage()); return false; } }

Target:
Is `e.getMessage()` used in the message? And, do we want the full stack trace of the exception, or do we just want the message?
Source:
public synchronized void updateTasks(List<TaskInfo> taskInfoList) { synchronized (mJobInfo) { for (TaskInfo taskInfo : taskInfoList) { mJobInfo.setTaskInfo(taskInfo.getTaskId(), taskInfo); } updateStatus(); } }

Target:
this synchronized block is redundant? remove the method synchronization then?
Source:
public synchronized void failTasksForWorker(long workerId) { Integer taskId = mWorkerIdToTaskId.get(workerId); if (taskId == null) { return; } TaskInfo taskInfo = mJobInfo.getTaskInfo(taskId); if (taskInfo.getStatus().isFinished()) { return; } synchronized (mJobInfo) { if (!mJobInfo.getStatus().isFinished()) { taskInfo.setStatus(Status.FAILED); taskInfo.setErrorMessage("Job worker was lost before the task could complete"); updateStatus(); } } }

Target:
same here. redundant synchronization?
Source:
private void shutdownManagedChannel(ManagedChannel managedChannel, long shutdownTimeoutMs) { managedChannel.shutdown(); try { managedChannel.awaitTermination(shutdownTimeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // Allow thread to exit. } finally { managedChannel.shutdownNow(); } Verify.verify(managedChannel.isShutdown()); }

Target:
Is this necessary?
Source:
private String getTransportPath(AlluxioURI uri) { if (uri.hasScheme()) { return uri.toString(); } else { return uri.getPath(); } }

Target:
It looks useful. How about make this a member method of `AlluxioURI` rather than a util method here (and if it stays here, I would even make it static method).
Source:
public Options getOptions() { return new Options() .addOption(FORCE_OPTION) .addOption(LIST_DIR_AS_FILE_OPTION) .addOption(LIST_HUMAN_READABLE_OPTION) .addOption(LIST_PINNED_FILES_OPTION) .addOption(TIMESTAMP_OPTION) .addOption(RECURSIVE_OPTION) .addOption(REVERSE_SORT_OPTION) .addOption(SORT_OPTION); }

Target:
NIT: Keep the options sorted alphabetically.
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof IdentityObject)) { // If it isn't an instance of an identity object, compare our internal pointer with the arg // A form of "auto unboxing" when performing comparisons return mObj == o; } try { IdentityObject<T> other = (IdentityObject<T>) o; return mObj == other.mObj; } catch (ClassCastException e) { return false; } }

Target:
This looks dangerous. It may hide some issues in the future if we change the implementation. Do we really need unboxing?
Source:
public synchronized JournalContext createJournalContext() throws UnavailableException { if (mState != State.PRIMARY) { // We throw UnavailableException here so that clients will retry with the next primary master. throw new UnavailableException("Failed to write to journal: journal is in state " + mState); } AsyncJournalWriter writer = mAsyncWriter; if (writer == null) { throw new UnavailableException("Failed to write to journal: journal is shutdown."); } return new MasterJournalContext(writer); }

Target:
Was this a bug? When could this happen?
Source:
public void createWithLengthLimit() throws Exception { String c256 = String.join("", Collections.nCopies(16, "0123456789ABCDEF")); assertEquals(256, c256.length()); mFileInfo.flags.set(O_WRONLY.intValue()); assertEquals(-ErrorCodes.ENAMETOOLONG(), mFuseFs.create("/foo/" + c256, 0, mFileInfo)); }

Target:
we don't need to assert `c256` as it is not a part of Alluxio logic :)
Source:
public static <T> void call(Logger logger, RpcCallableThrowsIOException<T> callable, String methodName, boolean failureOk, String description, StreamObserver<T> responseObserver, Object... args) { try { responseObserver .onNext(callAndReturn(logger, callable, methodName, failureOk, description, args)); responseObserver.onCompleted(); } catch (StatusException e) { responseObserver.onError(e); } }

Target:
Move this line out of the try-catch to avoid error due to calling onError on closed call?
Source:
protected String getRootKey() { if (mUri.getScheme() != null && mUri.getScheme().equals("s3a")) { return Constants.HEADER_S3A + mBucketName; } else { return Constants.HEADER_S3 + mBucketName; } }

Target:
`"s3a".equals(mUri.getScheme())`? Should we also check for `s3`, is there any risk of the uri scheme not being `s3a` or `s3`?
Source:
public boolean remove(T element) { return mQueue.removeIf(x -> x.mValue == element); }

Target:
NIT: use `getValue()` instead of accessing private member?
Source:
public GrpcChannel(GrpcManagedChannelPool.ChannelKey channelKey, Channel channel, long shutdownTimeoutMs) { mChannelKey = channelKey; mChannelHealthState = channel instanceof AuthenticatedChannel ? () -> (((AuthenticatedChannel) channel).isAuthenticated() && mChannelHealthy) : () -> mChannelHealthy; if (channel instanceof AuthenticatedChannel) { // Store {@link AuthenticatedChannel::#close) for signaling end of // authenticated session during shutdown. mAuthCloseCallback = ((AuthenticatedChannel) channel)::close; } mChannel = ClientInterceptors.intercept(channel, new ChannelResponseTracker((this))); mChannelReleased = false; mShutdownTimeoutMs = shutdownTimeoutMs; }

Target:
we do various things for the instance of `AuthenticatedChannel`. Can we just have a bool for that? Also, what other types of channels (not AuthenticatedChannel) are possible? All this checking looks like it can be abstracted away.
Source:
public Map<String, String> getXAttr() { return mXAttr; }

Target:
Can we use `byte[]` for attribute values? Given that we want to store encoded values, using `byte[]` is more compact and platform agnostic.
Source:
private CreateOptions(String authUmask) { mAcl = null; mCreateParent = false; mEnsureAtomic = false; // default owner and group are null (unset) mOwner = null; mGroup = null; mMode = ModeUtils.applyFileUMask(Mode.defaults(), authUmask); mXAttr = new HashMap<>(); }

Target:
This will be expensive(CPU, mem) to create repeatedly, especially if xattrs is never used. For example, maps have a default size (looks like 16) which can add up. Should we consider not creating the map at all if unused?
Source:
public synchronized void loadConfIfNotLoaded(InetSocketAddress address) throws AlluxioStatusException { boolean clusterConfLoaded = mClusterConf.clusterDefaultsLoaded(); boolean pathConfLoaded = mIsPathConfLoaded; loadConf(address, !clusterConfLoaded, !pathConfLoaded); }

Target:
nit: inline booleans
Source:
default String hash() { return null; }

Target:
how about an empty string instead?
Source:
public Version(Supplier<Stream<byte[]>> properties) { try { mMD5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } mProperties = properties; mShouldUpdate = new AtomicBoolean(true); mVersion = ""; }

Target:
why do we set this?
Source:
public int hashCode() { return Objects.hashCode( mCommonOptions, mAcl, mBlockSizeBytes, mGroup, mLocationPolicy, mMode, mMountId, mOwner, mReplicationDurable, mReplicationMax, mReplicationMin, mUfsPath, mWriteTier, mWriteType ); }

Target:
Can we use alphabetical order? :)
Source:
public void record(long timeNano, int numEvents) { long leftEndPoint = bucket(timeNano); mSeries.put(leftEndPoint, (mSeries.getOrDefault(leftEndPoint, 0)) + numEvents); }

Target:
You can remove the parentheses around `mSeries.getOrDefault(leftEndPoint, 0)` - they are no longer needed ```java mSeries.put(leftEndPoint, mSeries.getOrDefault(leftEndPoint, 0) + numEvents); ```
Source:
public Map<String, List<String>> getLostStorage() { return Collections.unmodifiableMap(mLostStorage); }

Target:
safer to create a copy here. Otherwise there could be a `ConcurrentModificationException` if one RPC tries to read the returned map while the map is being updated by another RPC.
Source:
public List<String> getLostStorage() { return Collections.unmodifiableList(mLostStorage); }

Target:
seems susceptible to concurrent modification exceptions. Could we return a copy instead?
Source:
public Map<String, List<String>> getDirectoryPathsOnTiers() { Map<String, List<String>> pathsOnTiers = new HashMap<>(); for (Pair<String, String> tierPath : mCapacityBytesOnDirs.keySet()) { String tier = tierPath.getFirst(); pathsOnTiers.computeIfAbsent(tier, k -> new ArrayList<>()); pathsOnTiers.get(tier).add(tierPath.getSecond()); } return pathsOnTiers; }

Target:
why not `xxx.computeIfAbsent(xxx).add(xxx)`, no reason to `get(tier)` again in the line below.
Source:
private void applyPathProperties(PathPropertiesEntry entry) { final String path = entry.getPath(); final Map<String, String> properties = entry.getPropertiesMap(); if (mProperties.containsKey(path)) { mProperties.get(path).clear(); mProperties.get(path).putAll(properties); } else { mProperties.put(path, new HashMap<>(properties)); } }

Target:
Is it necessary to keep the previous hashmap, could we just use put which will override?
Source:
private void applyRemovePathProperties(RemovePathPropertiesEntry entry) { final String path = entry.getPath(); mProperties.remove(path); }

Target:
nit: unnecessary final
Source:
public static Collection<? extends PropertyKey> defaultKeys() { return Sets.newHashSet(DEFAULT_KEYS_MAP.values() .parallelStream().filter(key -> !PropertyKey.isRemoved(key)) .collect(Collectors.toSet())); }

Target:
should we instead construct `DEFAULT_KEYS_MAP` so that it doesn't contain removed keys?
Source:
public LsCommand() { mExtensionsDir = ServerConfiguration.get(PropertyKey.EXTENSIONS_DIR); }

Target:
Because we can just call `ServerConfiguration.get` why don't we make an empty constructor here and just make the `ServerConfiguration` call when the command is actually executing. I think it just simplifies the code since the `mExtensionsDir` isn't used anywhere else
Source:
private ListObjectsV2Result getObjectListingChunk(ListObjectsV2Request request) throws IOException { AmazonClientOperation<ListObjectsV2Result> op = () -> { // Query S3 for the next batch of objects. ListObjectsV2Result result = mClient.listObjectsV2(request); // Advance the request continuation token to the next set of objects. request.setContinuationToken(result.getNextContinuationToken()); return result; }; try { return retry(op, "get next chunk of listing result"); } catch (AmazonClientException e) { throw new IOException(e); } }

Target:
can we inline the operations, similar to how we use `RpcUtils.call`?
Source:
public Response createDirectory(@PathParam("path") final String path, final CreateDirectoryPOptions options) { return RestUtils.call((RestUtils.RestCallable<Void>) () -> { if (options == null) { mFileSystem.createDirectory(new AlluxioURI(path), FileSystemOptions.createDirectoryDefaults(ServerConfiguration.global())); } else { mFileSystem.createDirectory(new AlluxioURI(path), options); } return null; }, ServerConfiguration.global()); }

Target:
This goes to FileSystem. Why do you need to supply the defaults here?
Source:
public void getStartTimeMs() throws Exception { Assert.assertTrue(getInfo(NO_PARAMS).getStartTimeMs() > 0); }

Target:
we prefer `assertX` over `Assert.assertX`
Source:
public synchronized void close() throws IOException { if (mWriter != null) { mWriter.close(); mWriter = null; mAsyncWriter.close(); mAsyncWriter = null; } if (mTailerThread != null) { mTailerThread.awaitTermination(false); mTailerThread = null; } mState = State.CLOSED; }

Target:
Do we need to check if `mAsyncWriter != null`?
Source:
public void release(int port) { Reservation r = mReserved.remove(port); if (r != null) { r.mFile.delete(); try { r.mLock.release(); r.mChannel.close(); } catch (IOException e) { throw new RuntimeException(e); } } }

Target:
this doesn't throw anything? And, we can delete a file, and then close its channel?
Source:
void startServing() { startServing("", ""); }

Target:
`private` if it's meant to be used within the class, `protected` if it's meant to be used by subclasses
Source:
public static BlockStore.Factory getBlockStoreFactory() { MetastoreType type = Configuration.getEnum(PropertyKey.MASTER_METASTORE, MetastoreType.class); switch (type) { case HEAP: return lockManger -> new HeapBlockStore(); case ROCKS: return args -> new RocksBlockStore(Configuration.global()); default: throw new IllegalStateException("Unknown metastore type: " + type); } }

Target:
NIT: "lockManger" -> "lockManager"
Source:
public void remove(Long inodeId) { System.out.printf("Remove %s from rocks%n", inodeId); try { byte[] id = Longs.toByteArray(inodeId); mDb.delete(mInodesColumn, mDisableWAL, id); } catch (RocksDBException e) { throw new RuntimeException(e); } }

Target:
old debugging output?
Source:
public void removeChild(String name) { if (mChildren.remove(name) != null) { mWeight.decrementAndGet(); } }

Target:
`mChildren` could be `null`
Source:
public void close() throws IOException { if (mClient.isShutdown()) { return; } mStream.close(); try { mStream.waitForComplete(CLOSE_TIMEOUT_MS); } finally { mContext.releaseBlockWorkerClient(mAddress, mClient); } }

Target:
If the client is shutdown, do we still need to release it?
Source:
private LocalFileDataReader(LocalFileBlockReader reader, long offset, long len, long chunkSize) throws IOException { mReader = reader; Preconditions.checkArgument(chunkSize > 0); mPos = offset; mEnd = Math.min(mReader.getLength(), offset + len); mChunkSize = chunkSize; }

Target:
Does this method throw IOException?
Source:
public static FileSystemContext create(Subject subject, MasterInquireClient masterInquireClient, AlluxioConfiguration alluxioConf) { AlluxioProperties props = null; if (alluxioConf != null) { props = alluxioConf.getProperties(); } FileSystemContext context = new FileSystemContext(subject, props); context.init(masterInquireClient); return context; }

Target:
Would it make sense to include `MasterInquireClient` in the `ClientContext` since the inquire client (how to find the alluxio master) is pretty central to any client. Then, I feel like the FileSystemContext really only needs 1 constructor that takes a `ClientContext`.
Source:
public static AlluxioConfiguration merge(AlluxioConfiguration conf, Map<?, ?> properties, Source source) { AlluxioProperties props = conf.getProperties(); props.merge(properties, source); return new InstancedConfiguration(props); }

Target:
does this modify the input `conf`?
Source:
public void close() throws IOException { mChannel.shutdown(); try { long timeout = Configuration.getMs(PropertyKey.WORKER_NETWORK_NETTY_SHUTDOWN_TIMEOUT); if (!mChannel.awaitTermination(timeout, TimeUnit.MILLISECONDS)) { LOGGER.warn("Timed out after {}ms to close gRPC channel to block worker.", timeout); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } }

Target:
Add worker host to log message
Source:
public void stop() throws IOException { if (mAsyncAuditLogWriter != null) { mAsyncAuditLogWriter.stop(); mAsyncAuditLogWriter = null; } super.stop(); mSyncManager.stop(); }

Target:
does this have to be stopped before `super.stop()`?
Source:
public List<alluxio.wire.SyncPointInfo> getSyncPathList() throws IOException, AlluxioException { FileSystemMasterClient masterClient = mFileSystemContext.acquireMasterClient(); try { return masterClient.getSyncPathList(); } catch (UnavailableException e) { throw e; } catch (AlluxioStatusException e) { throw e.toAlluxioException(); } finally { mFileSystemContext.releaseMasterClient(masterClient); } }

Target:
nit: why not import?
Source:
private static String newDbPath(String baseDir) { // We use a unique subdirectory to avoid conflicts with the previous RocksDB instance when we // re-create the db in initDB(). return PathUtils.concatPath(baseDir, "blocks-" + System.nanoTime() + "-" + CommonUtils.randomAlphaNumString(3)); }

Target:
Should we use `currentTimeMillis()` to have some ordering sense in the dir names?
Source:
public void createFileOutsideOfAlluxio(AlluxioURI uri) throws Exception { try (FileOutStream os = mFileSystem.createFile(uri, CreateFileOptions.defaults() .setWriteType(WriteType.THROUGH) .setBlockSizeBytes(TEST_BLOCK_SIZE))) { os.write(BufferUtils.getIncreasingByteArray(TEST_BLOCK_SIZE + 1)); } }

Target:
nit: should be private
Source:
private void assertBadAuthority(String authority, String failureMessage) throws Exception { try { useUriWithAuthority("zk@a:0,b:0,c:1"); fail(failureMessage); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), containsString("does not match")); } }

Target:
should the `zk@a:0,b:0,c:1` be change to `authority`?
Source:
public int getInt(PropertyKey key) { String rawValue = get(key); try { return Integer.parseInt(lookup(rawValue)); } catch (NumberFormatException e) { throw new RuntimeException(ExceptionMessage.KEY_NOT_INTEGER.getMessage(key)); } catch (UnresolvablePropertyException e) { throw new RuntimeException(e); } }

Target:
I think the `lookup` calls in the `getX` series of methods are unnecessary. `get(key)` will already call `lookup`, so the second `lookup` does nothing
Source:
public void noAuthorityNoWarning() throws IOException { URI unknown = URI.create("alluxio:///"); FileSystem.get(unknown, new org.apache.hadoop.conf.Configuration()); assertFalse(mTestLogger.mAppender.wasLogged("Authority \"\" is unknown")); }

Target:
for this case I think it's better not to log a warning. This is the recommended way to write an alluxio uri that picks up its authority from configuration.
Source:
public void run() { mLastHeartbeatThread.start(); try { // Shutdown hooks should run quickly, so we limit the wait time to 500ms. It isn't the end // of the world if the final heartbeat fails. mLastHeartbeatThread.join(500); if (mLastHeartbeatThread.isAlive()) { LOG.warn("Failed to heartbeat to the metrics master before exit"); } } catch (InterruptedException e) { return; } }

Target:
Should we put this in a finally?
Source:
public void close() throws IOException { // super.close should be called first before releasing the resources in this instance, as the // super class may invoke other methods in this class. For example, // org.apache.hadoop.fs.FileSystem.close may check the existence of certain temp files before // closing super.close(); synchronized (CACHED_CONTEXTS_LOCK) { Pair<FileSystemContext, AtomicInteger> contextAndRefCount = CACHED_CONTEXTS.get(mContext.getParentSubject()); if (contextAndRefCount == null) { LOG.warn("Failed to find context to close, have you called close multiple times?"); return; } if (contextAndRefCount.getSecond().decrementAndGet() == 0) { contextAndRefCount.getFirst().close(); } } }

Target:
can we push the reference counting and close implementation into `FileSystemContext`? It reads better than `getFirst()/getSecond()`.
Source:
public void mergeEmptyHadoopConfiguration() throws URISyntaxException { org.apache.hadoop.conf.Configuration hadoopConfig = new org.apache.hadoop.conf.Configuration(); long beforeSize = Configuration.toMap().size(); HadoopConfigurationUtils.mergeHadoopConfiguration(hadoopConfig, Configuration.global()); long afterSize = Configuration.toMap().size(); Assert.assertEquals(beforeSize, afterSize); Assert.assertFalse(Configuration.getBoolean(PropertyKey.ZOOKEEPER_ENABLED)); }

Target:
why throw this?
Source:
public String getHost() { if (getAuthorityType() == AuthorityType.SINGLE_MASTER) { SingleMasterAuthority authority = (SingleMasterAuthority) mUri.getAuthority(); return authority.getHost(); } return null; }

Target:
do we need the `getAuthorityType()` method? `instanceof` can be used in a similar way, and it makes it clearer that it will be safe to cast to the authority subclass
Source:
private TtlBucket getBucketContaining(Inode<?> inode) { if (inode.getTtl() <= Constants.NO_TTL) { // no bucket will contain a inode with NO_TTL. return null; } long ttlEndTimeMs = inode.getCreationTimeMs() + inode.getTtl(); // Gets the last bucket with interval start time less than or equal to the inode's life end // time. TtlBucket bucket = mBucketList.floor(new TtlBucket(ttlEndTimeMs)); if (bucket == null || bucket.getTtlIntervalEndTimeMs() < ttlEndTimeMs || (bucket.getTtlIntervalEndTimeMs() == ttlEndTimeMs && TtlBucket.getTtlIntervalMs() != 0)) { // 1. There is no bucket in the list, or // 2. All buckets' interval start time is larger than the inode's life end time, or // 3. No bucket actually contains ttlEndTimeMs in its interval. return null; } return bucket; }

Target:
Prefer the original or `inode.getTtl() < 0`.
Source:
public MetricsCommand(MetaMasterClient metaMasterClient, PrintStream printStream) throws IOException { mMetaMasterClient = metaMasterClient; mPrintStream = printStream; mMetricsMap = new TreeMap<>(mMetaMasterClient.getMetrics()); }

Target:
not good to perform expensive/blocking operations in the constructor - could we call this from `run()` instead?
Source:
public void setAcl(String path, AccessControlList acl) { // Noop here by default }

Target:
This might still need the `throws IOException` signature.
Source:
public synchronized ConfigCheckReport getConfigCheckReport() { if (mConfigDirty == true) { mConfigDirty = false; regenerateReport(); } return mConfigCheckReport; }

Target:
`if(mConfigDirty)`?
Source:
public T removeAcl(List<AclEntry> entries) throws IOException { for (AclEntry entry : entries) { if (entry.isDefault()) { AccessControlList defaultAcl = getDefaultACL(); if (defaultAcl != null) { defaultAcl.removeEntry(entry); } } else { mAcl.removeEntry(entry); } } return getThis(); }

Target:
Can `defaultAcl` be `null`?
Source:
public String stripPrefixIfPresent(String path) { String stripedKey = CommonUtils.stripPrefixIfPresent(path, PathUtils.normalizePath(getRootKey(), PATH_SEPARATOR)); if (!stripedKey.equals(path)) { return stripedKey; } return CommonUtils.stripPrefixIfPresent(path, PATH_SEPARATOR); }

Target:
Can we limit the scope?
Source:
LockedInodePath(AlluxioURI uri, InodeLockList lockList, InodeTree.LockMode lockMode) throws InvalidPathException { Preconditions.checkArgument(!lockList.getInodes().isEmpty()); mUri = uri; mPathComponents = PathUtils.getPathComponents(mUri.getPath()); mLockList = lockList; mLockMode = lockMode; }

Target:
`getInodes` is expensive, right? (new array, copying entries)
Source:
public boolean isOpen() { return mTransport != null && mTransport.isOpen(); }

Target:
we can add a precondition to the constructor that `mTransport` is non-null, then since it's final we don't need to check any more. At that point it might be worth inlining the `isOpen` calls
Source:
public ServerConfigurationChecker(ServerConfigurationStore masterStore, ServerConfigurationStore workerStore) { mMasterStore = masterStore; mWorkerStore = workerStore; mConfigCheckReport = new ConfigCheckReport(); mLastLogConfigReportTimeMs = System.currentTimeMillis(); mMasterStore.registerChangeListener(this::regenerateReport); }

Target:
initialize to -1 since we haven't logged a report yet?
Source:
public Address setHost(String host) { Preconditions.checkNotNull(host, "host"); mHost = host; return this; }

Target:
`checkNotNull` is designed to be chained like `mHost = Preconditions.checkNotNull(host, "host")`
Source:
public void before() throws Exception { GROUPS.put(IMPERSONATION_USER, IMPERSONATION_GROUP1 + "," + IMPERSONATION_GROUP2); GROUPS.put(HDFS_USER, HDFS_GROUP1 + "," + HDFS_GROUP2); // Give the root dir 777, to write files as different users. FileSystem.Factory.get().setAttribute(new AlluxioURI("/"), SetAttributeOptions.defaults().setMode(new Mode((short) 0777))); }

Target:
should these two go to the static `beforeClass`?
Source:
public String getId() { return mId; }

Target:
Is there any way to determine the ID of a process, how will users be able to map an ID to a process after seeing the metrics be abnormal?
Source:
public synchronized void heartbeat(final List<Metric> metrics) throws IOException { retryRPC(new RpcCallable<Void>() { @Override public Void call() throws TException { mClient.metricsHeartbeat(FileSystemContext.INSTANCE.getId(), NetworkAddressUtils.getClientHostName(), new MetricsHeartbeatTOptions(metrics)); return null; } }); }

Target:
The nested retries (`retryRPC` and `heartbeatThread`) may cause unneeded complexity?
Source:
public void clientHeartbeat(String clientId, String hostname, List<Metric> metrics) { if (metrics.isEmpty()) { return; } mMetricsStore.putClientMetrics(hostname, clientId, metrics); }

Target:
Could we do this logic in `putClientMetrics`, since it should be able to handle an empty set?
Source:
public static FileSystemContext get() { if (sInstance == null) { synchronized (FileSystemContext.class) { sInstance = create(); } } return sInstance; }

Target:
This is not safe, `sInstance` can be set multiple times?
Source:
private static void initializeGauges() { MetricsSystem.registerGaugeIfAbsent(MetricsSystem.getClientMetricName("NettyConnectionsOpen"), new Gauge<Long>() { @Override public Long getValue() { long ret = 0; for (NettyChannelPool pool : sInstance.mNettyChannelPools.values()) { ret += pool.size(); } return ret; } }); }

Target:
We might not always be using `sInstance` right? Based on the current implementation, each context object has its own metrics heartbeat, so this gauge should be based on the context?
Source:
public MetaCommand masterHeartbeat(long masterId) { MasterInfo master = mMasters.getFirstByField(ID_INDEX, masterId); if (master == null) { LOG.warn("Could not find master id: for heartbeat.", masterId); return MetaCommand.Register; } synchronized (master) { master.updateLastUpdatedTimeMs(); } return MetaCommand.Nothing; }

Target:
is this `synchronized` required?
Source:
protected void stopMasters() { try { mWorkerConfigChecker.reset(); mRegistry.stop(); } catch (IOException e) { throw Throwables.propagate(e); } }

Target:
Should this be moved to `startMasters`? @aaudiber
Source:
public alluxio.thrift.Metric toThrift() { alluxio.thrift.Metric metric = new alluxio.thrift.Metric(); metric.setInstance(mInstance); metric.setHostname(mHostname); metric.setName(mName); if (!(mValue instanceof Integer) && !(mValue instanceof Long)) { LOG.error("The value of metric %s is neither integer nor long", this); } metric.setValue(((Number) mValue).longValue()); return metric; }

Target:
can we make `mValue` type `Long`?
Source:
protected DefaultMetricsMaster(MasterContext masterContext) { this(masterContext, new SystemClock(), ExecutorServiceFactories .fixedThreadPoolExecutorServiceFactory(Constants.METRICS_MASTER_NAME, 2)); }

Target:
why protected?
Source:
public long getValue(Map<MetricsFilter, Set<Metric>> map) { long value = 0; for (Metric metric : map.get(mFilter)) { value += (long) metric.getValue(); } return value; }

Target:
is this cast necessary? I thought metrics should always be longs
Source:
public static Map<String, String> toMap() { Map<String, String> map = toRawMap(); // Resolve values with ${VALUE} format String nestedPropIdentifier = "$"; for (Map.Entry<String, String> entry : map.entrySet()) { String value = entry.getValue(); if (value != null && value.contains(nestedPropIdentifier)) { map.put(entry.getKey(), lookup(value)); } } return map; }

Target:
maybe a simpler approach here and better code reuse? ```java for (PropertyKey key : PropertyKey.defaultKeys()) { map.add(key.getName, get(key)); } return map; ```
Source:
public AccessControlList getAcl(String path) throws UnimplementedException, IOException { throw new UnimplementedException("ACL is not supported"); }

Target:
Instead of using an exception, could we return some default value?
Source:
public void testMetricsCapacity() { when(mBlockMaster.getCapacityBytes()).thenReturn(1000L); Assert.assertEquals(1000L, getGauge(Metrics.CAPACITY_TOTAL)); when(mBlockMaster.getUsedBytes()).thenReturn(200L); Assert.assertEquals(200L, getGauge(Metrics.CAPACITY_USED)); Assert.assertEquals(800L, getGauge(Metrics.CAPACITY_FREE)); }

Target:
nit: can just use `assertEquals`, similar to using `when` instead of `Mockito.when`
Source:
public CapacityCommand(BlockMasterClient blockMasterClient, PrintStream printStream) { mBlockMasterClient = blockMasterClient; mPrintStream = printStream; initValues(); }

Target:
what's the reasoning behind using this helper vs initializing in the constructor vs initializing during declaration?
Source:
public synchronized List<WorkerInfo> getWorkerReport( final GetWorkerReportOptions options) throws IOException { return retryRPC(new RpcCallable<List<WorkerInfo>>() { @Override public List<WorkerInfo> call() throws TException { List<WorkerInfo> result = new ArrayList<>(); for (alluxio.thrift.WorkerInfo workerInfo : mClient .getWorkerReport(options.toThrift()).getWorkerInfoList()) { result.add(ThriftUtils.fromThrift(workerInfo)); } return result; } }); }

Target:
NIT: can you use Java 8 lambda function to simplify the code? https://stackoverflow.com/questions/25270467/java-8-lambda-replace-anonymous-inner-class-by-lambda
Source:
public GetWorkerInfoListTResponse getWorkerInfoList(GetWorkerInfoListTOptions options) throws AlluxioTException { return RpcUtils.call(LOG, new RpcCallableThrowsIOException<GetWorkerInfoListTResponse>() { @Override public GetWorkerInfoListTResponse call() throws AlluxioException, AlluxioStatusException { List<WorkerInfo> workerInfos = new ArrayList<>(); for (alluxio.wire.WorkerInfo workerInfo : mBlockMaster.getWorkerInfoList()) { workerInfos.add(ThriftUtils.toThrift(workerInfo)); } return new GetWorkerInfoListTResponse(workerInfos); } }); }

Target:
nit: Java 8 lambda function
Source:
public Options getOptions() { return new Options() .addOption(LIVE_OPTION) .addOption(LOST_OPTION) .addOption(SPECIFIED_OPTION) .addOption(HELP_OPTION); }

Target:
sort
Source:
public String getDescription() { return "Report Alluxio running cluster information.\n" + "Where [category] is an optional argument. If no arguments are passed in, " + "summary information will be printed out.\n" + "[category] can be one of the following:\n" + " summary cluster summary\n" + " capacity worker capacity information\n"; }

Target:
I would sort the lines of these subcommands here
Source:
public BlockMasterInfo setCapacityBytesOnTiers(Map<String, Long> capacityBytesOnTiers) { mCapacityBytesOnTiers = new HashMap<>(); for (Map.Entry<String, Long> entry : capacityBytesOnTiers.entrySet()) { long capacity = entry.getValue(); if (capacity > 0) { mCapacityBytesOnTiers.put(entry.getKey(), capacity); } } return this; }

Target:
wire types are basic objects that store and retrieve data using simple getters and setters. There shouldn't be any non-trivial code like this. If we need to filter out negative capacities, it should be done outside of this class. To make a defensive copy, you can use `new HashMap<>(capacityBytesOnTiers)`
Source:
public int hashCode() { return Objects.hashCode(mLiveWorkerNum, mLostWorkerNum, mCapacityBytes, mUsedBytes, mFreeBytes, mCapacityBytesOnTiers, mUsedBytesOnTiers); }

Target:
nit: can you sort them by member var names? So in the future, adding a new member will have a deterministic location.
Source:
public RetryHandlingBlockMasterClient(MasterClientConfig conf) { super(conf); mClient = null; }

Target:
class member variable is `null` by default, typically we don't init null value.
Source:
public synchronized BlockMasterInfo getBlockMasterInfo(final Set<BlockMasterInfoField> fields) throws IOException { return retryRPC(() -> { Set<alluxio.thrift.BlockMasterInfoField> thriftFields = new HashSet<>(); if (fields == null) { thriftFields = null; } else { for (BlockMasterInfoField field : fields) { thriftFields.add(field.toThrift()); } } return ThriftUtils.fromThrift( mClient.getBlockMasterInfo(new GetBlockMasterInfoTOptions(thriftFields)) .getBlockMasterInfo()); }); }

Target:
nit: to simplify the code and a minor optimization (avoid creating unused `HashSet` instance): ```java Set<alluxio.thrift.BlockMasterInfoField> thriftFields = null; if (fields != null) { thriftFields = new HashSet<>(); for (BlockMasterInfoField field : fields) { ... } } ```
Source:
public void validateArgs(String... args) throws InvalidArgumentException { if (args.length > 2) { throw new InvalidArgumentException( ExceptionMessage.INVALID_ARGS_GENERIC.getMessage(getCommandName())); } }

Target:
isn't there only one arg, summary?
Source:
public ReportCommand() { mMetaMasterClient = new RetryHandlingMetaMasterClient(MasterClientConfig.defaults()); mBlockMasterClient = new RetryHandlingBlockMasterClient(MasterClientConfig.defaults()); mPrintStream = new PrintStream(System.out); }

Target:
why do we wrap `System.out` inside another `PrintStream`?
Source:
public boolean remove(@Nullable Object object) { if (object == null) { return false; } assert object != null : "@AssumeAssertion(nullness)"; // Locking this object protects against removing the exact object that might be in the // process of being added, but does not protect against removing a distinct, but equivalent // object. synchronized (object) { if (mPrimaryIndex != null && mPrimaryIndex.containsObject((T) object)) { // This isn't technically typesafe. However, given that success is true, it's very unlikely // that the object passed to remove is not of type <T>. @SuppressWarnings("unchecked") T tObj = (T) object; removeFromIndices(tObj); return true; } else { return false; } } }

Target:
is the above null check not enough to convince the checker framework that `object` is non-null at this point?
Source:
public Options getOptions() { return new Options() .addOption(RECURSIVE_OPTION) .addOption(FORCE_OPTION) .addOption(LIST_DIR_AS_FILE_OPTION) .addOption(LIST_PINNED_FILES_OPTION) .addOption(LIST_HUMAN_READABLE_OPTION) .addOption(SORT_OPTION) .addOption(REVERSE_SORT_OPTION); }

Target:
this wasn't alphabetized before, but it would be nice to now
Source:
public boolean isInSafeMode() { // bails out early before expensive clock checks if (!mWorkerConnectWaitStartTimeMs.isMarked()) { return false; } Long startTime = mWorkerConnectWaitStartTimeMs.getReference(); if (startTime == null) { // master has not started waiting for workers yet return true; } // lazily updates safe mode state upon inquiry long waitTime = Configuration.getMs(PropertyKey.MASTER_WORKER_CONNECT_WAIT_TIME); if (mClock.millis() - startTime < waitTime) { return true; } return !mWorkerConnectWaitStartTimeMs.compareAndSet(startTime, null, true, false); }

Target:
is this return value correct? If another thread comes in and brings us out of safe mode first, this will say we're still in safe mode.
Source:
public boolean validate(Map<String, String> optionsMap) { if (shouldSkip()) { return true; } if (!validateHdfsSettingParity(optionsMap)) { return false; } return true; }

Target:
Since this method is defined on the interface, it would make more sense for the ValidateEnv class to call this method and skip the task instead of doing it in each task.
Source:
protected void startServing(String startMessage, String stopMessage) { MetricsSystem.startSinks(); mSafeModeManager.notifyRpcServerStarted(); startServingWebServer(); startJvmMonitorProcess(); LOG.info("Alluxio master version started{}. " + "bindHost={}, connectHost={}, rpcPort={}, webPort={}", RuntimeConstants.VERSION, startMessage, NetworkAddressUtils.getBindAddress(ServiceType.MASTER_RPC), NetworkAddressUtils.getConnectAddress(ServiceType.MASTER_RPC), NetworkAddressUtils.getPort(ServiceType.MASTER_RPC), NetworkAddressUtils.getPort(ServiceType.MASTER_WEB)); startServingRPCServer(); LOG.info("Alluxio master ended{}", stopMessage); }

Target:
we should do this immediately before calling `mThriftServer.serve()` in `startServingRPCServer`
Source:
private void init(long offset) throws BlockDoesNotExistException, IOException { UnderFileSystem ufs = mUfsManager.get(mBlockMeta.getMountId()).getUfs(); ufs.connectFromWorker( NetworkAddressUtils.getConnectHost(NetworkAddressUtils.ServiceType.WORKER_RPC)); try { updateUnderFileSystemInputStream(offset); } catch (IOException e) { throw new BlockDoesNotExistException( ExceptionMessage.UFS_PATH_DOES_NOT_EXIST.getMessage(mBlockMeta.getUnderFileSystemPath()), e); } updateBlockWriter(offset); }

Target:
Is it guaranteed that the `IOException` will be because of the path not existing?
Source:
protected ObjectUnderFileSystem(AlluxioURI uri, UnderFileSystemConfiguration ufsConf) { super(uri, ufsConf); int numThreads = Configuration.getInt(PropertyKey.UNDERFS_OBJECT_STORE_SERVICE_THREADS); mExecutorService = ExecutorServiceFactories.fixedThreadPoolExecutorServiceFactory( "alluxio-underfs-object-service-worker", numThreads).create(); mOpenRetryBaseSleepMs = (int) Configuration.getMs(PropertyKey.UNDERFS_OBJECT_STORE_READ_RETRY_BASE_SLEEP_MS); mOpenRetryMaxSleepMs = (int) Configuration.getMs(PropertyKey.UNDERFS_OBJECT_STORE_READ_RETRY_MAX_SLEEP_MS); mOpenRetryMaxNum = Configuration.getInt(PropertyKey.UNDERFS_OBJECT_STORE_READ_RETRY_MAX_NUM); }

Target:
Is the configuration call expensive? Otherwise I suggest to just do this lookup in the open call since the values will not be used anywhere else.
Source:
public long getPos() { try { return ((FSDataInputStream) in).getPos(); } catch (IOException e) { throw new RuntimeException("Failed to get position " + e); } }

Target:
Is this a good idea, this will kill the thread arbitrarily?
Source:
public static LocalAlluxioMaster create(final String workDirectory) throws IOException { if (!Files.isDirectory(Paths.get(workDirectory))) { Files.createDirectory(Paths.get(workDirectory)); } Configuration.set(PropertyKey.MASTER_SAFEMODE_WAIT, "0ms"); return new LocalAlluxioMaster(); }

Target:
Move this to ConfigurationTestUtils#testConfigurationDefaults
Source:
public void addInodeDirectoryFromJournal(InodeDirectoryEntry entry) throws AccessControlException { InodeDirectory directory = InodeDirectory.fromJournalEntry(entry); if (directory.getName().equals(ROOT_INODE_NAME)) { // This is the root inode. Clear all the state, and set the root. reset(); setRoot(directory); // If journal entry has no security enabled, change the replayed inode permission to be 0777 // for backwards-compatibility. if (SecurityUtils.isSecurityEnabled() && entry.hasMode()) { mRoot.setMode(Constants.DEFAULT_FILE_SYSTEM_MODE); } } else { addInodeFromJournalInternal(directory, entry.hasMode()); } }

Target:
should this be !entry.hasMode()?
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FreeOptions)) { return false; } FreeOptions that = (FreeOptions) o; return Objects.equal(mForced, that.mForced) && Objects.equal(mCommonOptions, that.mCommonOptions) && Objects.equal(mRecursive, that.mRecursive); }

Target:
can you sort ?
Source:
public int hashCode() { return Objects.hashCode(mLoadMetadataType, mCommonOptions); }

Target:
ditto and others.
Source:
public int hashCode() { return Objects .hashCode(mAllowExists, mMode, mRecursive, mTtl, mTtlAction, mWriteType, mCommonOptions); }

Target:
sort
Source:
public static void printHelp(String message) { System.err.println(message); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(USAGE, null, OPTIONS, null, true); }

Target:
(nit) You can probably use the shorter version `formatter.printHelp(USAGE, OPTIONS, true);`
Source:
protected void updateStreams() throws IOException { long blockId = mPositionState.getBlockId(); if (blockId == mCurrentBlockId && mCurrentBlockInStream != null && mCurrentBlockInStream.remaining() != 0) { return; } checkCacheStreamInSync(); updateBlockInStream(blockId); if (PASSIVE_CACHE_ENABLED) { updateCacheStream(blockId); } mCurrentBlockId = blockId; mCurrentBlockStartPos = mPositionState.getBlockStartPos(); mCurrentBlockEndPos = mPositionState.getNextBlockStartPos(); }

Target:
Can we use the state in `mPositionState` instead of using the other member variables?
Source:
public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) { future.channel().close(); } try (LockResource lr = new LockResource(mLock)) { if (future.cause() != null) { updateException(future.cause()); mDoneOrFailed.signal(); mBufferNotFullOrFailed.signal(); mBufferEmptyOrFailed.signal(); } } }

Target:
Do we want to signal even if there is no cause but the future returns failure?