auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>String getHealthReport() { <START> String healthReport = ""; <END> String scriptReport = (nodeHealthScriptRunner == null) ? "" : nodeHealthScriptRunner.getHealthReport(); String discReport = dirsHandler.getDisksHealthReport(false); String exceptionReport = nodeHealthException != null ? nodeHealthException.getMessage() : ""; if (!scriptReport.equals("")) { healthReport = scriptReport; } if (!discReport.equals("")) { healthReport = healthReport.equals("") ? discReport : healthReport.concat(SEPARATOR + discReport); } if (!exceptionReport.equals("")) { healthReport = healthReport.equals("") ? exceptionReport : healthReport.concat(SEPARATOR + exceptionReport); } return healthReport; }</code><technical_language>This a bit cleaner a Joiner: String scriptReport = (nodeHealthScriptRunner == null) ? null : nodeHealthScriptRunner.getHealthReport(); String discReport = dirsHandler.getDisksHealthReport(false); String exceptionReport = nodeHealthException == null ? null : nodeHealthException.getMessage(); String healthReport = Joiner.on(SEPARATOR).skipNulls().join(scriptReport, discReport.equals("") ? null : discReport, exceptionReport); discReport throws a monkey wrench in works returning "" instead of null. a more elegant solution I above..</technical_language>

Target:
String getHealthReport() { String scriptReport = nullIfEmpty(nodeHealthScriptRunner == null ? null : nodeHealthScriptRunner.getHealthReport()); String discReport = nullIfEmpty(dirsHandler.getDisksHealthReport(false)); String exceptionReport = nullIfEmpty(nodeHealthException == null ? null : nodeHealthException.getMessage()); return Joiner.on(SEPARATOR).skipNulls() .join(scriptReport, discReport, exceptionReport); }
Source:
<code>private String emailMask(String email){ String[] frag = email.split("@"); int sid = frag[0].length() / 3 + 1; int sdomain = frag[1].length() / 3 + 1; String id = frag[0].substring(0, sid) + "*****"; <START> String domain = "***" + frag[1].substring(sdomain); END> return id + "@" + domain; }</code><technical_language>I love +1 guarantee a letter visible. Is a reason for asterisks in id vs. domain of length? I find confusing if email test@example.org te***@***le.org te*****@***le.org</technical_language>

Target:
private String emailMask(String email){ String[] frag = email.split("@"); int sid = frag[0].length() / 3 + 1; int sdomain = frag[1].length() / 3; String id = frag[0].substring(0, sid) + "***"; String domain = "***" + frag[1].substring(sdomain); return id + "@" + domain; }
Source:
<code>public void toggleAllSelected(){ <START> System.out.print("in toggle all"); <END> this.selectAllFiles = !this.selectAllFiles; toggleSelectedFiles(this.selectAllFiles); }</code><technical_language>please remove this System.out.print convert logger.fine if valuable debugging in production</technical_language>

Target:
public void toggleAllSelected(){ this.selectAllFiles = !this.selectAllFiles; }
Source:
<code>private static String getMessageClass(ReceiveCommand.Type type) { String mc = ""; switch (type) { case CREATE: <START> mc = "newBranch"; <END> break; case UPDATE: mc = "modifyBranch"; break; case DELETE: mc = "deleteBranch"; break; } return mc; }</code><technical_language>Nit: return "newBranch"; is simpler, need for "break"s "String mc" then</technical_language>

Target:
private static String getMessageClass(ReceiveCommand.Type type) { switch (type) { case CREATE: return "newBranch"; case UPDATE: return "modifyBranch"; case DELETE: return "deleteBranch"; default: return "errorBranch"; } }
Source:
<code>public Range<Long> visitLimit(LimitNode node, Void context) { Range<Long> sourceCardinalityRange = node.getSource().accept(this, null); <START> return Range.closed(sourceCardinalityRange.lowerEndpoint(), min(sourceCardinalityRange.upperEndpoint(), node.getCount())); <END> }</code><technical_language>sourceCardinalityRange.lowerEndpoint() higher node.getCount(), range incorrect</technical_language>

Target:
public Range<Long> visitLimit(LimitNode node, Void context) { Range<Long> sourceCardinalityRange = node.getSource().accept(this, null); long upper = node.getCount(); if (sourceCardinalityRange.hasUpperBound()) { upper = min(sourceCardinalityRange.upperEndpoint(), node.getCount()); } long lower = min(upper, sourceCardinalityRange.lowerEndpoint()); return Range.closed(lower, upper); }
Source:
<code>private Iterable<ChangeData> queryRecentChanges(int limit) throws OrmException { QueryProcessor qp = queryProcessor.get(); qp.setLimit(limit); <START> String query = "project:{" + projectName + "} is:open"; <END> try { return Iterables.limit(queryProcessor.get().queryChanges(query), limit); } catch (QueryParseException e) { throw new IllegalStateException(e); } }</code><technical_language>hand a text query. Build predicate graph hand</technical_language>

Target:
private Iterable<ChangeData> queryRecentChanges(int limit) throws OrmException { QueryProcessor qp = queryProcessor.get(); qp.setLimit(limit); ChangeQueryBuilder qb = qp.getQueryBuilder(); Predicate<ChangeData> p = Predicate.and(qb.project(projectName.get()), qb.status_open()); try { return Iterables.limit(qp.queryChanges(p), limit); } catch (QueryParseException e) { throw new OrmException(e); } }
Source:
<code><START> public Boolean isActiveProject(int id) { <END> Project project = getProject(id); return project != null; }</code><technical_language>this method is longer? call ?Should remove it? Besides, method name sounds a bit confused here. detect exist here, active, right</technical_language>

Target:
public Boolean isActiveProject(int id) { return getProject(id) != null; }
Source:
<code>public void robotInit() { try { DOMConfigurator.configure("log4j.xml"); } catch (Exception e) { <START> log.error("Couldn't configure logging - file probably missing or malformed"); <END> } this.injector = Guice.createInjector(this.injectionModule); this.initializeSystems(); SmartDashboard.putData(Scheduler.getInstance()); frequencyReportInterval = injector.getInstance(XPropertyManager.class).createPersistentProperty("Robot loop frequency report interval", 20); }</code><technical_language>I System.out intentional log in this case. do both</technical_language>

Target:
public void robotInit() { try { DOMConfigurator.configure("log4j.xml"); } catch (Exception e) { final String errorString = "Couldn't configure logging - file probably missing or malformed"; System.out.println(errorString); DriverStation.reportError(errorString, false); } this.injector = Guice.createInjector(this.injectionModule); this.initializeSystems(); SmartDashboard.putData(Scheduler.getInstance()); frequencyReportInterval = injector.getInstance(XPropertyManager.class).createPersistentProperty("Robot loop frequency report interval", 20); }
Source:
<code>public OffsetDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException { <START> return (OffsetDateTime) rs.getObject(columnIndex); <END> }</code><technical_language>argument of getObject() instead of cast. suggestion return rs.getObject(columnIndex, OffsetDateTime.class);</technical_language>

Target:
public OffsetDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return rs.getObject(columnIndex, OffsetDateTime.class); }
Source:
<code>public <B extends RenderedReport.Builder<B, ?>> CompletableFuture<B> render( final S source, final F format, final TimeRange timeRange, final B builder, final Duration timeout ) { final DevToolsService dts = _devToolsFactory.create(getIgnoreCertificateErrors(source)); LOGGER.debug() .setMessage("rendering") .addData("source", source) .addData("format", format) .addData("timeRange", timeRange) .log(); final CompletableFuture<Void> navigate = dts.navigate(getUri(source).toString()); final CompletableFuture<B> result = navigate .thenCompose(whatever -> { LOGGER.debug() .setMessage("page load completed") .addData("source", source) .addData("format", format) .addData("timeRange", timeRange) .log(); return whenLoaded(dts, source, format, timeRange, builder); }); result.whenComplete((x, e) -> { LOGGER.debug() .setMessage("rendering completed") .addData("source", source) .addData("format", format) .addData("timeRange", timeRange) .addData("result", x) <START> .addData("exception", e) <END> .log(); navigate.cancel(true); dts.close(); }); TIMEOUT_SERVICE.schedule(() -> result.cancel(true), timeout.toNanos(), TimeUnit.NANOSECONDS); return result; }</code><technical_language>add exception .setThrowable</technical_language>

Target:
public <B extends RenderedReport.Builder<B, ?>> CompletableFuture<B> render( final S source, final F format, final TimeRange timeRange, final B builder, final Duration timeout ) { final DevToolsService dts = _devToolsFactory.create(getIgnoreCertificateErrors(source)); LOGGER.debug() .setMessage("rendering") .addData("source", source) .addData("format", format) .addData("timeRange", timeRange) .log(); final CompletableFuture<Void> navigate = dts.navigate(getUri(source).toString()); final CompletableFuture<B> result = navigate .thenCompose(whatever -> { LOGGER.debug() .setMessage("page load completed") .addData("source", source) .addData("format", format) .addData("timeRange", timeRange) .log(); return whenLoaded(dts, source, format, timeRange, builder); }); result.whenComplete((x, e) -> { LOGGER.debug() .setMessage("rendering completed") .addData("source", source) .addData("format", format) .addData("timeRange", timeRange) .addData("result", x) .setThrowable(e) .log(); navigate.cancel(true); dts.close(); }); TIMEOUT_SERVICE.schedule(() -> result.cancel(true), timeout.toNanos(), TimeUnit.NANOSECONDS); return result; }
Source:
<code>public void processStartTransactionsUpdate( Set<Long> startTimestamps, LockWatchStateUpdate update) { Optional<IdentifiedVersion> latestVersion = processEventLogUpdate(update); latestVersion.ifPresent( version -> startTimestamps.forEach(timestamp -> timestampMap.putStartVersion(timestamp, version))); <START> getEarliestVersion().ifPresent(eventLog::removeOldEntries); <END> }</code><technical_language>This feels in wrong place? cleaning transactions removed cache, added right? Otherwise, this prompt</technical_language>

Target:
public void processStartTransactionsUpdate( Set<Long> startTimestamps, LockWatchStateUpdate update) { Optional<IdentifiedVersion> updateVersion = processEventLogUpdate(update); updateVersion.ifPresent(version -> timestampStateStore.putStartTimestamps(startTimestamps, version)); retentionEventsInLog(); }
Source:
<code>public static List<Ignite> allGrids() { List<Ignite> res = IgnitionEx.allGrids(); <START> if (res == null || res.isEmpty()) <END> return res; Ignite ignite = res.get(0); if (ignite instanceof IgniteEx && insideSandbox()) return res.stream().map((i) -> sandboxIgniteProxy(i, false)).collect(Collectors.toList()); return res; }</code><technical_language>F.isEmpty()</technical_language>

Target:
public static List<Ignite> allGrids() { List<Ignite> res = IgnitionEx.allGrids(); if (F.isEmpty(res)) return res; if (isInsideSandbox()) return res.stream().map(Ignition::wrapToProxy).collect(Collectors.toList()); return res; }
Source:
<code>public void init() { check = () -> { try { kuid = randomUUID().toString(); client = KurentoClient.create(kurentoWsUrl, new KConnectionListener(kuid)); client.getServerManager().addObjectCreatedListener(new KWatchDogCreate()); <START> client.getServerManager().addObjectDestroyedListener(new KWatchDogDestroy()); <END> } catch (Exception e) { log.warn("Fail to create Kurento client, will re-try in ms", checkTimeout); kmsRecheckScheduler.schedule(check, checkTimeout, MILLISECONDS); } }; check.run(); }</code><technical_language>relying browser events <LINK_0> stream stopped destroyed I investigate is happening</technical_language>

Target:
public void init() { check = () -> { try { kuid = randomUUID().toString(); client = KurentoClient.create(kurentoWsUrl, new KConnectionListener(kuid)); client.getServerManager().addObjectCreatedListener(new KWatchDogCreate()); client.getServerManager().addObjectDestroyedListener(new EventListener<>() { @Override public void onEvent(ObjectDestroyedEvent event) { log.debug("Kurento::ObjectDestroyedEvent objectId {}, tags {}, source {}", event.getObjectId(), event.getTags(), event.getSource()); } }); } catch (Exception e) { log.warn("Fail to create Kurento client, will re-try in ms", checkTimeout); kmsRecheckScheduler.schedule(check, checkTimeout, MILLISECONDS); } }; check.run(); }
Source:
<code>public synchronized boolean put(String key, String value) { SQLiteDatabase db = this.getWritableDatabase(); try { db.execSQL("INSERT OR REPLACE INTO " + TABLE_NAME + " (" + COL_KEY + ", " + COL_VALUE + ") " + " VALUES('" + key + "', '" + value + "')"); } catch (SQLException ignored) { <START> return false; <END> } finally { db.close(); } return true; }</code><technical_language>a wider exception idea if sql exception happens. deal exception itself</technical_language>

Target:
public synchronized boolean put(String key, String value) { SQLiteDatabase db = this.getWritableDatabase(); try { db.execSQL("INSERT OR REPLACE INTO " + TABLE_NAME + " (" + COL_KEY + ", " + COL_VALUE + ") " + " VALUES('" + key + "', '" + value + "')"); } catch (Exception ignored) { return false; } finally { db.close(); } return true; }
Source:
<code>public void start() { ScriptEngine engine = orcsApi.getScriptEngine(); resources.add(new OrcsScriptResource(engine)); classes.add(BranchesResource.class); resources.add(new IdeClientEndpointImpl()); resources.add(new BranchEndpointImpl(orcsApi, resourceManager, activityLog)); resources.add(new OrcsWriterEndpointImpl(orcsApi)); resources.add(new TransactionEndpointImpl(orcsApi)); resources.add(new TypesEndpointImpl(orcsApi)); resources.add(new IndexerEndpointImpl(orcsApi)); resources.add(new ResourcesEndpointImpl(resourceManager)); <START> resources.add(new DatastoreEndpointImpl(orcsApi, activityLog)); <END> resources.add(new LinkUpdateResource(orcsApi)); }</code><technical_language>This is necessary for client work, removed</technical_language>

Target:
public void start() { ScriptEngine engine = orcsApi.getScriptEngine(); resources.add(new OrcsScriptResource(engine)); classes.add(BranchesResource.class); resources.add(new IdeClientEndpointImpl()); resources.add(new BranchEndpointImpl(orcsApi, resourceManager, activityLog)); resources.add(new OrcsWriterEndpointImpl(orcsApi)); resources.add(new TransactionEndpointImpl(orcsApi)); resources.add(new TypesEndpointImpl(orcsApi)); resources.add(new IndexerEndpointImpl(orcsApi)); resources.add(new ResourcesEndpointImpl(resourceManager)); resources.add(new DatastoreEndpointImpl(orcsApi, activityLog)); resources.add(new KeyValueResource(orcsApi)); resources.add(new LinkUpdateResource(orcsApi)); }
Source:
<code>public void onUpgradeAlreadyOccurred() { final int oldVersion = DatabaseHelper.DATABASE_VERSION; final int newVersion = DatabaseHelper.DATABASE_VERSION; final TableDefaultsCustomizer customizer = mock(TableDefaultsCustomizer.class); mDistanceTable.onUpgrade(mSQLiteDatabase, oldVersion, newVersion, customizer); <START> verify(mSQLiteDatabase, atLeast(0)).execSQL(mSqlCaptor.capture()); <END> verifyZeroInteractions(customizer); }</code><technical_language>change atLeast(0) here? This test aims determine SQL logic executed DB version</technical_language>

Target:
public void onUpgradeAlreadyOccurred() { final int oldVersion = DatabaseHelper.DATABASE_VERSION; final int newVersion = DatabaseHelper.DATABASE_VERSION; final TableDefaultsCustomizer customizer = mock(TableDefaultsCustomizer.class); mDistanceTable.onUpgrade(mSQLiteDatabase, oldVersion, newVersion, customizer); verify(mSQLiteDatabase, never()).execSQL(mSqlCaptor.capture()); verifyZeroInteractions(customizer); }
Source:
<code>private GlusterVolumeTaskStatusEntity fetchRemobeBricksStatusDetails() { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeRemoveBricksStatus, new GlusterVolumeRemoveBricksVDSParameters(getUpServerId(clusterId), volume.getName(), getParameters().getBricks(), volume.getReplicaCount())); GlusterVolumeTaskStatusEntity entity = (GlusterVolumeTaskStatusEntity) returnValue.getReturnValue(); GlusterAsyncTask asyncTask = volume.getAsyncTask(); if (asyncTask != null) { Guid taskId = asyncTask.getTaskId(); <START> if (taskId != null) { <END> List<Step> stepsList = getStepDao().getStepsByExternalId(taskId); if (stepsList != null && !stepsList.isEmpty()) { entity.setStartTime(stepsList.get(0).getStartTime()); } } } return entity; }</code><technical_language>more readable if (asyncTask != null && asyncTask.getTaskId() != null ) { ... }</technical_language>

Target:
private GlusterVolumeTaskStatusEntity fetchRemobeBricksStatusDetails() { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeRemoveBricksStatus, new GlusterVolumeRemoveBricksVDSParameters(getUpServerId(clusterId), volume.getName(), getParameters().getBricks(), volume.getReplicaCount())); GlusterVolumeTaskStatusEntity entity = (GlusterVolumeTaskStatusEntity) returnValue.getReturnValue(); GlusterAsyncTask asyncTask = volume.getAsyncTask(); if (asyncTask != null && asyncTask.getTaskId() != null) { List<Step> stepsList = getStepDao().getStepsByExternalId(asyncTask.getTaskId()); if (stepsList != null && !stepsList.isEmpty()) { entity.setStartTime(stepsList.get(0).getStartTime()); } } return entity; }
Source:
<code>protected void dropAllDatabaseObjects() throws SQLException { Statement statement = null; try { statement = connection.createStatement(); String query = "DROP ALL OBJECTS"; statement.execute(query); } catch (JdbcSQLNonTransientException e) { <START> log.info("connection is already closed, most likely a test method already dropped all database objects"); <END> } finally { connection.close(); } }</code><technical_language>log.info log.error</technical_language>

Target:
protected void dropAllDatabaseObjects() throws SQLException { Statement statement = null; try { statement = connection.createStatement(); String query = "DROP ALL OBJECTS"; statement.execute(query); } catch (JdbcSQLNonTransientException e) { log.error("connection is already closed, most likely a test method already dropped all database objects"); } finally { connection.close(); } }
Source:
<code>void testResourceCreateFailure() { server.expect().post().withPath("/api/v1/namespaces/test/pods").andReturn(HttpURLConnection.HTTP_BAD_REQUEST, new PodBuilder() .withNewMetadata().withResourceVersion("12345").endMetadata().build()).once(); KubernetesClient client = server.getClient(); <START> assertThrows(KubernetesClientException.class, () -> client.resource(new PodBuilder().withNewMetadata().withName("pod123").endMetadata().build()).createOrReplace()); <END> }</code><technical_language>sonar issues here. In order exception is thrown in right place: suggestion Pod pod = client.resource(new PodBuilder().withNewMetadata().withName("pod123").endMetadata().build()); // assertThrows(KubernetesClientException.class, () -> pod.createOrReplace()); for rest of warnings</technical_language>

Target:
void testResourceCreateFailure() { server.expect().post().withPath("/api/v1/namespaces/test/pods").andReturn(HttpURLConnection.HTTP_BAD_REQUEST, new PodBuilder() .withNewMetadata().withResourceVersion("12345").endMetadata().build()).once(); KubernetesClient client = server.getClient(); NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicable<Pod, Boolean> podOperation = client.resource(new PodBuilder().withNewMetadata().withName("pod123").endMetadata().build()); assertThrows(KubernetesClientException.class, podOperation::createOrReplace); }
Source:
<code>protected Future<Slice> getAsyncManagedState(Object tuple) { <START> Future<Slice> valFuture = ((ManagedTimeStateImpl)managedState).getAsync(getBucketId(getKey(tuple)), <END> getKey(tuple)); return valFuture; }</code><technical_language>getKey called once. need call for parameters of getAsync</technical_language>

Target:
protected Future<Slice> getAsyncManagedState(Object tuple) { Slice key = getKey(tuple); Future<Slice> valFuture = ((ManagedTimeStateImpl)managedState).getAsync(getBucketId(key), key); return valFuture; }
Source:
<code>private static String logContent(byte[] content, String contentEncoding) { String contentString; try { contentString = new String(content, contentEncoding); } catch (UnsupportedEncodingException e) { <START> contentString = ""; <END> } return AnonymizerUtil.anonymize(contentString); }</code><technical_language>Logging added here, ensure if is wrong..</technical_language>

Target:
private static String logContent(byte[] content, String contentEncoding) { String contentString; try { contentString = new String(content, contentEncoding); } catch (UnsupportedEncodingException e) { contentString = "We were not able to encode the content: " + e.getMessage(); } return AnonymizerUtil.anonymize(contentString); }
Source:
<code>public final ChannelPipeline addLast(String name, ChannelHandler handler) { checkMultiplicity(handler); if (name == null) { name = generateName(handler); } AbstractChannelHandlerContext newCtx = newContext(name, handler); EventExecutor executor = executor(); <START> boolean inEventLoop = executor().inEventLoop(); <END> synchronized (this) { if (context(name) != null) { throw new IllegalArgumentException("Duplicate handler name: " + name); } handlers.add(newCtx); if (!inEventLoop) { try { executor.execute(() -> addLast0(newCtx)); return this; } catch (Throwable cause) { handlers.remove(newCtx); throw cause; } } } addLast0(newCtx); return this; }</code><technical_language>executor() -> executor</technical_language>

Target:
public final ChannelPipeline addLast(String name, ChannelHandler handler) { checkMultiplicity(handler); if (name == null) { name = generateName(handler); } AbstractChannelHandlerContext newCtx = newContext(name, handler); EventExecutor executor = executor(); boolean inEventLoop = executor.inEventLoop(); synchronized (this) { if (context(name) != null) { throw new IllegalArgumentException("Duplicate handler name: " + name); } handlers.add(newCtx); if (!inEventLoop) { try { executor.execute(() -> addLast0(newCtx)); return this; } catch (Throwable cause) { handlers.remove(handlers.size() - 1); throw cause; } } } addLast0(newCtx); return this; }
Source:
<code>public LazyECPoint(ECCurve curve, byte[] bits) { this.curve = curve; this.bits = bits; <START> this.compressed = (bits[0] == 2 || bits[0] == 3); <END> }</code><technical_language>This new ECKey.isPubKeyCompressed() helper I committed</technical_language>

Target:
public LazyECPoint(ECCurve curve, byte[] bits) { this.curve = curve; this.bits = bits; this.compressed = ECKey.isPubKeyCompressed(bits); }
Source:
<code>public Result createExternalIdentifier() throws Exception { UserSession session = getAuthenticatedSession(); <START> studyService.getStudy(session.getStudyIdentifier()); <END> AccountId accountId = AccountId.forHealthCode(session.getStudyIdentifier().getIdentifier(), session.getHealthCode()); ExternalIdentifier externalId = parseJson(request(), ExternalIdentifier.class); externalId.setStudyId(accountId.getStudyId()); Account account = accountDao.getAccount(accountId); ExternalIdentifier extIdObj = externalIdService.beginAssignExternalId(account, externalId.getIdentifier()); externalIdService.commitAssignExternalId(extIdObj); sessionUpdateService.updateExternalId(session, externalId); return okResult(UserSessionInfo.toJSON(session)); }</code><technical_language>Study service returns null if study exist. In practice, this happen session created study existing, delete studies in prod. However, in this case, if calling studyService.getStudy() extra service call anything</technical_language>

Target:
public Result createExternalIdentifier() throws Exception { UserSession session = getAuthenticatedSession(); AccountId accountId = AccountId.forHealthCode(session.getStudyIdentifier().getIdentifier(), session.getHealthCode()); ExternalIdentifier externalId = parseJson(request(), ExternalIdentifier.class); externalId.setStudyId(accountId.getStudyId()); participantService.assignExternalId(accountId, externalId); sessionUpdateService.updateExternalId(session, externalId); return okResult(UserSessionInfo.toJSON(session)); }
Source:
<code>public void moveSelectedPathToParentPath() { fVariablesTreeContentProvider.addPath(new Path(ID_GROUP1)); fVariablesTreeContentProvider.addPath(new Path(ID_GROUP1_SUBGROUP1)); fVariablesTreeContentProvider.addPath(new Path(ID_GROUP1_SUBGROUP1_SUBGROUP11)); fVariablesTreeContentProvider.moveSelectedPath(new Path("/group1/subgroup11"), new Path("/group1/subgroup1/subgroup11")); final Object[] actualAdditionalPathSubgroup1 = fVariablesTreeContentProvider.getChildren(new Path(ID_GROUP1).makeRelative()); assertEquals(2, actualAdditionalPathSubgroup1.length); assertEquals(new Path("group1/subgroup1"), actualAdditionalPathSubgroup1[0]); assertEquals(new Path("group1/subgroup11"), actualAdditionalPathSubgroup1[1]); <START> assertTrue(!fVariablesTreeContentProvider.hasChildren(new <END> Path(ID_GROUP1_SUBGROUP1))); }</code><technical_language>asserFalse() in cases avoid negotiation of result</technical_language>

Target:
public void moveSelectedPathToParentPath() { fVariablesTreeContentProvider.addPath(new Path(ID_GROUP1)); fVariablesTreeContentProvider.addPath(new Path(ID_GROUP1_SUBGROUP1)); fVariablesTreeContentProvider.addPath(new Path(ID_GROUP1_SUBGROUP1_SUBGROUP11)); fVariablesTreeContentProvider.moveSelectedPath(new Path("/group1/subgroup11"), new Path("/group1/subgroup1/subgroup11")); final Object[] actualAdditionalPathSubgroup1 = fVariablesTreeContentProvider.getChildren(new Path(ID_GROUP1).makeRelative()); assertEquals(2, actualAdditionalPathSubgroup1.length); assertEquals(new Path("group1/subgroup1"), actualAdditionalPathSubgroup1[0]); assertEquals(new Path("group1/subgroup11"), actualAdditionalPathSubgroup1[1]); assertFalse(fVariablesTreeContentProvider.hasChildren(new Path(ID_GROUP1_SUBGROUP1))); }
Source:
<code>public abstract void read(BitBuffer input) throws CTFReaderException; protected static void alignRead(BitBuffer input, IDeclaration declaration) throws CTFReaderException { long align = declaration.getAlignment(); long position = input.position(); <START> long pos = position + ((align - (position % align)) % align); <END> input.position(pos); }</code><technical_language>input.position(), position pos... this is confusing! re-use pos names</technical_language>

Target:
public abstract void read(BitBuffer input) throws CTFReaderException; protected static void alignRead(BitBuffer input, IDeclaration declaration) throws CTFReaderException{ long mask = declaration.getAlignment() -1; long pos = input.position(); if ((pos & mask) == 0) { return; } pos = (pos + mask) & ~mask; input.position(pos); }
Source:
<code>protected boolean isDetachAllowed() { if (getStoragePoolIsoMap() == null) { return failValidation(EngineMessage.STORAGE_DOMAIN_NOT_ATTACHED_TO_STORAGE_POOL); } <START> List<StorageDomain> storageDomains = storageDomainDao.getAllForStoragePool(getStoragePool().getId()); <END> if (storageDomains.size() > 1 && isMaster()) { return failValidation(EngineMessage.ERROR_CANNOT_DETACH_LAST_STORAGE_DOMAIN); } return true; }</code><technical_language>move this if, perform redundant queries</technical_language>

Target:
protected boolean isDetachAllowed() { if (getStoragePoolIsoMap() == null) { return failValidation(EngineMessage.STORAGE_DOMAIN_NOT_ATTACHED_TO_STORAGE_POOL); } if (isMaster() && storageDomainDao.getAllForStoragePool(getStoragePoolId()).size() > 1) { return failValidation(EngineMessage.ERROR_CANNOT_DETACH_LAST_STORAGE_DOMAIN); } return true; }
Source:
<code>private AuditEvents doListAuditEvents(final String uri) { try { return restTemplate.getForObject(uri, AuditEvents.class); } catch (GoodDataRestException e) { if (UNAUTHORIZED.value() == e.getStatusCode()) { throw new AuditEventsForbiddenException(e); } else { throw e; } } catch (RestClientException e) { <START> throw new GoodDataException("Unable to list audit events"); <END> } }</code><technical_language>I suggest including uri in exception message</technical_language>

Target:
private AuditEvents doListAuditEvents(final String uri) { try { return restTemplate.getForObject(uri, AuditEvents.class); } catch (GoodDataRestException e) { if (UNAUTHORIZED.value() == e.getStatusCode()) { throw new AuditEventsForbiddenException(e); } else { throw e; } } catch (RestClientException e) { throw new GoodDataException("Unable to list audit events: " + uri); } }
Source:
<code>public void spread_element() throws Exception { SpreadElementTree tree = parse("var x = [1, ... expression];", Kind.SPREAD_ELEMENT); assertThat(tree.is(Kind.SPREAD_ELEMENT)).isTrue(); <START> assertThat(tree.ellipsis().text()).isEqualTo(JavaScriptPunctuator.ELLIPSIS.getValue()); <END> }</code><technical_language>@vilchik-elena test tree.element()</technical_language>

Target:
public void spread_element() throws Exception { SpreadElementTree tree = parse("var x = [1, ... expression];", Kind.SPREAD_ELEMENT); assertThat(tree.is(Kind.SPREAD_ELEMENT)).isTrue(); assertThat(tree.ellipsis().text()).isEqualTo(JavaScriptPunctuator.ELLIPSIS.getValue()); assertThat(tree.element().is(Kind.IDENTIFIER_REFERENCE)).isTrue(); }
Source:
<code>public void init() { log.info("Start initializing " + getClass().getSimpleName()); List<VDS> allVdsList = DbFacade.getInstance().getVdsDao().getAll(); HashSet<Guid> nonResponsiveVdss = new HashSet<Guid>(); for (VDS helper_vds : allVdsList) { if (helper_vds.getStatus() == VDSStatus.NonResponsive) { nonResponsiveVdss.add(helper_vds.getId()); } } boolean runningVmsInTransition = false; List<VM> vms = DbFacade.getInstance().getVmDao().getAll(); for (VM vm : vms) { if (!vm.isNotRunning()) { if (vm.getRunOnVds() != null) { MultiValueMapUtils.addToMap(vm.getRunOnVds(), vm.getId(), _vdsAndVmsList, new MultiValueMapUtils.HashSetCreator<Guid>()); } if (vm.getRunOnVds() != null && nonResponsiveVdss.contains(vm.getRunOnVds())) { SetVmUnknown(vm); } } if (!runningVmsInTransition && vm.isRunning() && vm.getStatus() != VMStatus.Up) { runningVmsInTransition = true; } } for (VDS _vds : allVdsList) { boolean _saveVdsDynamic = false; <START> if (_vds.getPendingVcpusCount() != 0 && !runningVmsInTransition) { <END> _vds.setPendingVcpusCount(0); _saveVdsDynamic = true; } if (_vds.getPendingVmemSize() != 0 && !runningVmsInTransition) { _vds.setPendingVmemSize(0); _saveVdsDynamic = true; } if (_saveVdsDynamic) { DbFacade.getInstance().getVdsDynamicDao().update(_vds.getDynamicData()); } } for (VDS curVds : allVdsList) { AddVds(curVds, true); } IrsBrokerCommand.Init(); log.info("Finished initializing " + getClass().getSimpleName()); }</code><technical_language>runningVmsInTransition is host? is related? e.g. nonresponsive host's VMs consider "in transition" affecting other hosts</technical_language>

Target:
public void init() { log.info("Start initializing " + getClass().getSimpleName()); List<VDS> allVdsList = DbFacade.getInstance().getVdsDao().getAll(); HashSet<Guid> nonResponsiveVdss = new HashSet<Guid>(); for (VDS helper_vds : allVdsList) { if (helper_vds.getStatus() == VDSStatus.NonResponsive) { nonResponsiveVdss.add(helper_vds.getId()); } } List<VM> vms = DbFacade.getInstance().getVmDao().getAll(); for (VM vm : vms) { if (!vm.isNotRunning()) { if (vm.getRunOnVds() != null) { MultiValueMapUtils.addToMap(vm.getRunOnVds(), vm.getId(), _vdsAndVmsList, new MultiValueMapUtils.HashSetCreator<Guid>()); } if (vm.getRunOnVds() != null && nonResponsiveVdss.contains(vm.getRunOnVds())) { SetVmUnknown(vm); } } } for (VDS _vds : allVdsList) { boolean _saveVdsDynamic = false; boolean runningVmsInTransition = false; List<VM> _vms = DbFacade.getInstance().getVmDao().getAllRunningForVds(_vds.getId()); for (VM vm : _vms) { if (vm.isRunning() && vm.getStatus() != VMStatus.Up) { runningVmsInTransition = true; break; } } if (_vds.getPendingVcpusCount() != 0 && !runningVmsInTransition) { _vds.setPendingVcpusCount(0); _saveVdsDynamic = true; } if (_vds.getPendingVmemSize() != 0 && !runningVmsInTransition) { _vds.setPendingVmemSize(0); _saveVdsDynamic = true; } if (_saveVdsDynamic) { DbFacade.getInstance().getVdsDynamicDao().update(_vds.getDynamicData()); } } for (VDS curVds : allVdsList) { AddVds(curVds, true); } IrsBrokerCommand.Init(); log.info("Finished initializing " + getClass().getSimpleName()); }
Source:
<code>public void phoneSignIn() throws Exception { TestUtils.mockPlayContextWithJson(PHONE_SIGN_IN); Metrics metrics = new Metrics(TEST_REQUEST_ID); doReturn(metrics).when(controller).getMetrics(); when(authenticationService.phoneSignIn(any(), any())).thenReturn(userSession); Result result = controller.phoneSignIn(); <START> assertEquals(200, result.status()); <END> verify(authenticationService).phoneSignIn(contextCaptor.capture(), signInCaptor.capture()); CriteriaContext context = contextCaptor.getValue(); assertEquals(TEST_STUDY_ID_STRING, context.getStudyIdentifier().getIdentifier()); SignIn captured = signInCaptor.getValue(); assertEquals(TEST_STUDY_ID_STRING, captured.getStudyId()); assertEquals(TEST_TOKEN, captured.getToken()); assertEquals(TestConstants.PHONE.getNumber(), captured.getPhone().getNumber()); }</code><technical_language>Is worth verifying result contains a user session</technical_language>

Target:
public void phoneSignIn() throws Exception { response = mockPlayContextWithJson(PHONE_SIGN_IN); when(authenticationService.phoneSignIn(any(), any())).thenReturn(userSession); Result result = controller.phoneSignIn(); assertEquals(200, result.status()); JsonNode node = TestUtils.getJson(result); assertEquals(TEST_SESSION_TOKEN, node.get("sessionToken").textValue()); assertEquals("UserSessionInfo", node.get("type").textValue()); verify(authenticationService).phoneSignIn(contextCaptor.capture(), signInCaptor.capture()); CriteriaContext context = contextCaptor.getValue(); assertEquals(TEST_STUDY_ID_STRING, context.getStudyIdentifier().getIdentifier()); SignIn captured = signInCaptor.getValue(); assertEquals(TEST_STUDY_ID_STRING, captured.getStudyId()); assertEquals(TEST_TOKEN, captured.getToken()); assertEquals(TestConstants.PHONE.getNumber(), captured.getPhone().getNumber()); verifyCommonLoggingForSignIns(); }
Source:
<code>public void execute() { if (getRoleId() == null || getRoleId() < 1L) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Invalid role id provided"); } Role role = roleService.findRole(getRoleId()); if (role == null) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Invalid role id provided"); <START> } <END> CallContext.current().setEventDetails("Role id: " + role.getId()); boolean result = roleService.deleteRole(role); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); }</code><technical_language>Consider extracting this validation logic a private method more readable</technical_language>

Target:
public void execute() { Role role = roleService.findRole(getRoleId()); if (role == null) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Cannot find the role with provided id"); } CallContext.current().setEventDetails("Role id: " + role.getId()); boolean result = roleService.deleteRole(role); SuccessResponse response = new SuccessResponse(getCommandName()); response.setSuccess(result); setResponseObject(response); }
Source:
<code>public Task(String name, TaskTriggerInformation trigger, List<TaskActionInformation> actions, TaskConfig taskConfig, boolean enabled, boolean hasRegisteredChannel) { this.name = name; this.actions = actions == null ? new ArrayList<TaskActionInformation>() : actions; this.trigger = trigger; this.enabled = enabled; this.hasRegisteredChannel = hasRegisteredChannel; this.taskConfig = taskConfig == null ? new TaskConfig() : taskConfig; this.validationErrors = new HashSet<>(); this.failuresInRow = 0; this.numberOfRetries = DEFAULT_NUMBER_FOR_TASK_RETRIES; this.retryIntervalInMilliseconds = DEFAULT_TIME_FOR_RETRY_INTERVAL; this.useTimeWindow = false; this.startTime = null; <START> this.endTime = null; <END> }</code><technical_language>this is redundant</technical_language>

Target:
public Task(String name, TaskTriggerInformation trigger, List<TaskActionInformation> actions, TaskConfig taskConfig, boolean enabled, boolean hasRegisteredChannel) { this.name = name; this.actions = actions == null ? new ArrayList<TaskActionInformation>() : actions; this.trigger = trigger; this.enabled = enabled; this.hasRegisteredChannel = hasRegisteredChannel; this.taskConfig = taskConfig == null ? new TaskConfig() : taskConfig; this.validationErrors = new HashSet<>(); this.failuresInRow = 0; this.numberOfRetries = DEFAULT_NUMBER_FOR_TASK_RETRIES; this.retryIntervalInMilliseconds = DEFAULT_TIME_FOR_RETRY_INTERVAL; }
Source:
<code>public boolean isNavMenuVisible() { <START> return !menuView.getAttribute("class").contains("collapsed"); <END> }</code><technical_language>getAttribute returns null - add null check</technical_language>

Target:
public boolean isNavMenuVisible() throws WebDriverException { if (menuView.getAttribute("class") == null) { throw new WebDriverException("Expected String but got null"); } return !menuView.getAttribute("class").contains("collapsed"); }
Source:
<code>public int countFeatureTargets(EObject seedSource, EStructuralFeature feature) { if (feature.isMany()){ <START> return ((List<?>)seedSource.eGet(feature)).size(); <END> } return seedSource.eGet(feature) == null ? 0 : 1; }</code><technical_language>I thought base index do model traversal. I understand, this allows for removal of table in statsStore other hand, unintended side effects. For example: - behave in for dynamic EMF? - if seed is a proxy? - isMany() imply returned is a list, cast throw exceptions. - state of model state of index</technical_language>

Target:
public int countFeatureTargets(EObject seedSource, EStructuralFeature feature) { return instanceStore.getHolderToFeatureToValueMap().get(seedSource, toKey(feature)).size(); }
Source:
<code>public void stop() { if (isStarted.compareAndSet(true, false)) { stopQueue(); dispatcher.stop(); } <START> if (config.getPersistentQueueMode() == PersistentQueueMode.STICKY_POLLING) { <END> reaper.stop(); } }</code><technical_language>I call stop of mode (and stop is a no-op if started). way, implement other modes, update piece of code</technical_language>

Target:
public void stop() { if (isStarted.compareAndSet(true, false)) { stopQueue(); dispatcher.stop(); } reaper.stop(); }
Source:
<code>public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException { MultiValueTable<String, String> headers = new MultiValueTable<String, String>(); if (request.isPartSet("dismiss-user-alert")) { int userAlertHashCode = request.getIntPart("disable", -1); ctx.getAlertManager().dismissAlert(userAlertHashCode); } String redirect; try { redirect = request.getPartAsStringThrowing("redirectToAfterDisable", 1024); } catch (SizeLimitExceededException | NoSuchElementException e) { redirect = "."; } <START> headers.put("Location", redirect); <END> ctx.sendReplyHeaders(302, "Found", headers, null, 0); }</code><technical_language>This right is called open-redirect vulnerability. <LINK_0></technical_language>

Target:
public void handleMethodPOST(URI uri, HTTPRequest request, ToadletContext ctx) throws ToadletContextClosedException, IOException { MultiValueTable<String, String> headers = new MultiValueTable<String, String>(); if (request.isPartSet("dismiss-user-alert")) { int userAlertHashCode = request.getIntPart("disable", -1); ctx.getAlertManager().dismissAlert(userAlertHashCode); } String redirect; try { redirect = request.getPartAsStringThrowing("redirectToAfterDisable", 1024); } catch (SizeLimitExceededException | NoSuchElementException e) { redirect = "."; } if (!("/alerts/".equals(redirect) || "/".equals(redirect) || "/#bookmarks".equals(redirect))) { redirect = "."; } headers.put("Location", redirect); ctx.sendReplyHeaders(302, "Found", headers, null, 0); }
Source:
<code>protected void copyFile() throws CVSException { FileChannel tempFileChannel=null; FileChannel fileChannel=null; <START> try (FileInputStream <END> tempFileStream = new FileInputStream(tempFile); FileOutputStream fileStream = new FileOutputStream(file)){ tempFileChannel = tempFileStream.getChannel(); fileChannel = fileStream.getChannel(); long size= tempFileChannel.size(); long bytesTransferred = fileChannel.transferFrom(tempFileChannel, 0, size); while (bytesTransferred != size){ bytesTransferred += fileChannel.transferFrom(tempFileChannel, bytesTransferred, size); } } catch (IOException e) { throw CVSException.wrapException(e); } finally { if (tempFileChannel!=null) try { tempFileChannel.close(); } catch (IOException e) { throw CVSException.wrapException(e); } if (fileChannel!=null) try { fileChannel.close(); } catch (IOException e) { throw CVSException.wrapException(e); } if (tempFile != null) tempFile.delete(); } }</code><technical_language>finally block close underlying channels. closing redundant</technical_language>

Target:
protected void copyFile() throws CVSException { try (FileInputStream tempFileStream = new FileInputStream(tempFile); FileOutputStream fileStream = new FileOutputStream(file)) { FileChannel tempFileChannel = tempFileStream.getChannel(); FileChannel fileChannel = fileStream.getChannel(); long size = tempFileChannel.size(); long bytesTransferred = fileChannel.transferFrom(tempFileChannel, 0, size); while (bytesTransferred != size) { bytesTransferred += fileChannel.transferFrom(tempFileChannel, bytesTransferred, size); } } catch (IOException e) { throw CVSException.wrapException(e); } finally { if (tempFile != null) tempFile.delete(); } }
Source:
<code>public SlaveComputer(Slave slave) { super(slave); <START> this.log = new RewindableFileOutputStream(getLogFile()); <END> this.taskListener = new StreamTaskListener(decorate(this.log)); assert slave.getNumExecutors()!=0 : "Computer created with 0 executors"; }</code><technical_language>do want some rolling here</technical_language>

Target:
public SlaveComputer(Slave slave) { super(slave); this.log = new RewindableRotatingFileOutputStream(getLogFile(), 10); this.taskListener = new StreamTaskListener(decorate(this.log)); assert slave.getNumExecutors()!=0 : "Computer created with 0 executors"; }
Source:
<code>protected final void extractAdditionalFields(NitroItemSource<SOURCE> source, ITEM item, DateTime now) { ImmutableSetMultimap<String, Broadcast> broadcasts = extractBroadcasts(source.getBroadcasts(), now); OptionalMap<String, Set<Encoding>> encodings = extractEncodings(source.getAvailabilities(), now); ImmutableSet.Builder<Version> versions = ImmutableSet.builder(); for (com.metabroadcast.atlas.glycerin.model.Version nitroVersion : source.getVersions()) { Version version = new Version(); if (nitroVersion.getDuration() != null) { version.setDuration(convertDuration(nitroVersion.getDuration())); } version.setLastUpdated(now); version.setCanonicalUri(BbcFeeds.nitroUriForPid(nitroVersion.getPid())); version.setBroadcasts(broadcasts.get(nitroVersion.getPid())); Optional<Set<Encoding>> optEncodings = encodings.get(nitroVersion.getPid()); if (optEncodings.isPresent()) { Set<Encoding> versionEncodings = optEncodings.get(); for (Encoding encoding: versionEncodings) { encoding.setVideoAspectRatio(nitroVersion.getAspectRatio()); encoding.setAudioDescribed(isVersionOfType(nitroVersion, AUDIO_DESCRIBED_VERSION_TYPE)); encoding.setSigned(isVersionOfType(nitroVersion, SIGNED_VERSION_TYPE)); version.setManifestedAs(versionEncodings); } } Optional<WarningText> warningText = warningTextFrom(nitroVersion); version.setRestriction(generateRestriction(warningText)); versions.add(version); <START> } <END> item.setVersions(versions.build()); if (item instanceof Film) { item.setMediaType(MediaType.VIDEO); item.setSpecialization(Specialization.FILM); } else { extractMediaTypeAndSpecialization(source, item); } extractAdditionalItemFields(source, item, now); }</code><technical_language>I extract logic builds Atlas Version a separate method for clarity</technical_language>

Target:
protected final void extractAdditionalFields(NitroItemSource<SOURCE> source, ITEM item, DateTime now) { ImmutableSetMultimap<String, Broadcast> broadcasts = extractBroadcasts(source.getBroadcasts(), now); OptionalMap<String, Set<Encoding>> encodings = extractEncodings(source.getAvailabilities(), now); ImmutableSet.Builder<Version> versions = ImmutableSet.builder(); for (com.metabroadcast.atlas.glycerin.model.Version nitroVersion : source.getVersions()) { Version version = generateVersion(now, broadcasts, encodings, nitroVersion); versions.add(version); } item.setVersions(versions.build()); if (item instanceof Film) { item.setMediaType(MediaType.VIDEO); item.setSpecialization(Specialization.FILM); } else { extractMediaTypeAndSpecialization(source, item); } extractAdditionalItemFields(source, item, now); }
Source:
<code>public Set<String> undocumentedParameters() { <START> return elementParameters.stream() <END> .filter(name -> isEmptyDescription(blockTagDescriptions.get(BlockTagKey.of(BlockTag.PARAM, name)))) .collect(Collectors.toSet()); }</code><technical_language>worth computing once, store in local private variable (to prevent called multiple time in a row trigger computation.)</technical_language>

Target:
public List<String> undocumentedParameters() { return undocumentedNamedTags.computeIfAbsent(BlockTag.PARAM, key -> computeUndocumentedParameters()); }
Source:
<code><START> private static ContinuousStream<HashMap<String, Tuple2<Object, CepValueType>>> cepInputTranslator( <END> final MISTQueryBuilder queryBuilder, final CepInput cepInput) { if (cepInput.getInputType() == CepInputType.TEXT_SOCKET_SOURCE) { String sourceHostname = cepInput.getSourceConfiguration().get("SOCKET_INPUT_ADDRESS").toString(); int sourcePort = (int) cepInput.getSourceConfiguration().get("SOCKET_INPUT_PORT"); SourceConfiguration sourceConf = new TextSocketSourceConfiguration().newBuilder() .setHostAddress(sourceHostname) .setHostPort(sourcePort) .build(); return queryBuilder.socketTextStream(sourceConf) .map(s -> CepTuple.stringToMap(s, cepInput.getFields(), cepInput.getSeparator())); } else { throw new IllegalStateException("No other source is ready yet!"); } }</code><technical_language>HashMap -> Map</technical_language>

Target:
private static ContinuousStream<Map<String, Object>> cepInputTranslator( final MISTQueryBuilder queryBuilder, final CepInput cepInput) { switch (cepInput.getInputType()) { case TEXT_SOCKET_SOURCE: { final String sourceHostname = cepInput.getSourceConfiguration().get("SOCKET_INPUT_ADDRESS").toString(); final int sourcePort = (int) cepInput.getSourceConfiguration().get("SOCKET_INPUT_PORT"); final SourceConfiguration sourceConf = new TextSocketSourceConfiguration().newBuilder() .setHostAddress(sourceHostname) .setHostPort(sourcePort) .build(); final List<Tuple2<String, CepValueType>> fields = cepInput.getFields(); final String separator = cepInput.getSeparator(); return queryBuilder.socketTextStream(sourceConf) .map(new CepStringToMapFunction(fields, separator)); } default: throw new IllegalStateException("No other source is ready yet!"); } }
Source:
<code>public void childAdded(final TaskChild child, final boolean userThread) throws InvalidTransactionStateException { assert ! holdsLock(this); int state; synchronized (this) { if (currentState() == STATE_EXECUTE) { <START> children.add(child); <END> unfinishedChildren++; unvalidatedChildren++; unterminatedChildren++; state = nextState(userThread, NO_FLAGS); } else { if (userThread) { throw new IllegalStateException("Dependent may not be added at this point"); } else { return; } } } executeTasks(state); }</code><technical_language>I do this change re-reads of state field optimized JVM. in other tests performance of reading fields is measurably worse of local variables (which read weaker ordering rules JVM); in task case especially aware of this running thousands millions of tasks in a transaction</technical_language>

Target:
public void childAdded(final TaskChild child, final boolean userThread) throws InvalidTransactionStateException { assert ! holdsLock(this); int state; synchronized (this) { state = this.state; if (stateIsIn(state, STATE_EXECUTE)) { children.add(child); unfinishedChildren++; unvalidatedChildren++; unterminatedChildren++; if (userThread) state |= FLAG_USER_THREAD; state = transition(state); this.state = state & PERSISTENT_STATE; } else { if (userThread) { throw new IllegalStateException("Dependent may not be added at this point"); } else { return; } } } executeTasks(state); }