auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean isValidAttributes(RepositoryNode node, IElement elem) { if (node == null) { return true; } HadoopClusterConnection hcConnection = HCRepositoryUtil.getRelativeHadoopClusterConnection(node.getId()); DistributionBean hadoopDistribution = HadoopDistributionsHelper.HADOOP.getDistribution( hcConnection.getDistribution(), false); if (elem != null) { <START> if ((elem.getClass().getName().contains("MapReduceProcess")) <END> && "Cloudera_CDH580_Spark2".equals(hcConnection.getDfVersion())) { return false; } } if (attributesMap != null && !attributesMap.isEmpty()) { if (hcConnection != null) { if (hadoopDistribution != null) { DistributionVersion distributionVersion = hadoopDistribution.getVersion(hcConnection.getDfVersion(), false); if (distributionVersion != null && distributionVersion.hadoopComponent != null) { boolean validated = true; Object isSpark = attributesMap.get(ISSPARK); if (isSpark != null && Boolean.valueOf(isSpark.toString())) { validated = (validated && distributionVersion.hadoopComponent instanceof SparkComponent); if (!validated) { return false; } } Object useYarn = attributesMap.get(USEYARN); if (useYarn != null && Boolean.valueOf(useYarn.toString())) { validated = (validated && distributionVersion.hadoopComponent.isHadoop2()); if (!validated) { return false; } } } } } } return true; }</code><technical_language>Please "if (ComponentCategory.CATEGORY_4_MAPREDUCE.getName().equals(process.getComponentsType()))" instead this hard-coded way</technical_language>

Target:
private boolean isValidAttributes(RepositoryNode node, IElement elem) { if (node == null) { return true; } HadoopClusterConnection hcConnection = HCRepositoryUtil.getRelativeHadoopClusterConnection(node.getId()); DistributionBean hadoopDistribution = HadoopDistributionsHelper.HADOOP.getDistribution(hcConnection.getDistribution(), false); if ((elem != null) && (elem instanceof org.talend.designer.core.ui.editor.process.Process)) { if ((ComponentCategory.CATEGORY_4_MAPREDUCE.getName() .equals(((org.talend.designer.core.ui.editor.process.Process) elem).getComponentsType())) && "Cloudera_CDH580_Spark2".equals(hcConnection.getDfVersion())) { return false; } } if (attributesMap != null && !attributesMap.isEmpty()) { if (hcConnection != null) { if (hadoopDistribution != null) { DistributionVersion distributionVersion = hadoopDistribution.getVersion(hcConnection.getDfVersion(), false); if (distributionVersion != null && distributionVersion.hadoopComponent != null) { boolean validated = true; Object isSpark = attributesMap.get(ISSPARK); if (isSpark != null && Boolean.valueOf(isSpark.toString())) { validated = (validated && distributionVersion.hadoopComponent instanceof SparkComponent); if (!validated) { return false; } } Object useYarn = attributesMap.get(USEYARN); if (useYarn != null && Boolean.valueOf(useYarn.toString())) { validated = (validated && distributionVersion.hadoopComponent.isHadoop2()); if (!validated) { return false; } } } } } } return true; }
Source:
<code>public Object[][] incorrectContentTestData() { return new Object[][] { {"services: \n" + " dev-machine: \n" + " image: codenvy/ubuntu_jdk8\n" + " environment:\n" + " true", <START> "Parsing of environment configuration failed. Unsupported type 'class java.lang.Boolean'.*(?s).*" <END> }, {"services: \n" + " dev-machine: \n" + " image: codenvy/ubuntu_jdk8\n" + " environment:\n" + " - MYSQL_ROOT_PASSWORD: root\n", "Parsing of environment configuration failed. Unsupported value '\\[\\{MYSQL_ROOT_PASSWORD=root}]'.*(?s).*" }, {"services: \n" + " dev-machine: \n" + " image: codenvy/ubuntu_jdk8\n" + " environment:\n" + " MYSQL_ROOT_PASSWORD", "Parsing of environment configuration failed. Unsupported value 'MYSQL_ROOT_PASSWORD'.*(?s).*" }, {"services: \n" + " dev-machine: \n" + " image: codenvy/ubuntu_jdk8\n" + " environment:\n" + " - MYSQL_ROOT_PASSWORD=root\n" + " - MYSQL_DATABASE\n", "Parsing of environment configuration failed. Unsupported value 'MYSQL_DATABASE'.*(?s).*" }, {"services: \n" + " dev-machine: \n" + " image: codenvy/ubuntu_jdk8\n" + " environment:\n" + " =value ", "Parsing of environment configuration failed. Unsupported value '=value'.*(?s).*" }, {"services: \n" + " dev-machine: \n" + " image: codenvy/ubuntu_jdk8\n" + " environment:\n" + " VAR=val=1", "Parsing of environment configuration failed. Unsupported value 'VAR=val=1'.*(?s).*" }, }; }</code><technical_language>do need .* (?s). is enough I think. Mb \\.(?s).*</technical_language>

Target:
public Object[][] incorrectContentTestData() { return new Object[][] { {"services: \n" + " dev-machine: \n" + " image: codenvy/ubuntu_jdk8\n" + " environment:\n" + " true", "Parsing of environment configuration failed. Unsupported type 'class java.lang.Boolean'\\.(?s).*" }, {"services: \n" + " dev-machine: \n" + " image: codenvy/ubuntu_jdk8\n" + " environment:\n" + " - MYSQL_ROOT_PASSWORD: root\n", "Parsing of environment configuration failed. Unsupported value '\\[\\{MYSQL_ROOT_PASSWORD=root}]'\\.(?s).*" }, {"services: \n" + " dev-machine: \n" + " image: codenvy/ubuntu_jdk8\n" + " environment:\n" + " MYSQL_ROOT_PASSWORD", "Parsing of environment configuration failed. Unsupported value 'MYSQL_ROOT_PASSWORD'\\.(?s).*" }, {"services: \n" + " dev-machine: \n" + " image: codenvy/ubuntu_jdk8\n" + " environment:\n" + " VAR=val=1", "Parsing of environment configuration failed. Unsupported value 'VAR=val=1'\\.(?s).*" }, {"services: \n" + " dev-machine: \n" + " image: codenvy/ubuntu_jdk8\n" + " environment:\n" + " - MYSQL_ROOT_PASSWORD=root\n" + " - MYSQL_DATABASE\n", "Parsing of environment configuration failed. Unsupported value 'MYSQL_DATABASE'\\.(?s).*" }, }; }
Source:
<code>public Iterable<Payload> slice(Payload input, long size) { checkNotNull(input); <START> checkArgument(size >= 0, "length is negative"); <END> ContentMetadata meta = BaseMutableContentMetadata.fromContentMetadata(input.getContentMetadata()) .toBuilder() .contentLength(size) .contentMD5(null) .build(); if (input.getRawContent() instanceof File) { return doSlice((File) input.getRawContent(), meta); } else if (input.getRawContent() instanceof String) { return doSlice((String) input.getRawContent(), meta); } else if (input.getRawContent() instanceof byte[]) { return doSlice((byte[]) input.getRawContent(), meta); } else if (input.getRawContent() instanceof InputStream) { return doSlice((InputStream) input.getRawContent(), meta); } else { return doSlice(input, meta); } }</code><technical_language>Change "size non-negative was: %d"</technical_language>

Target:
public Iterable<Payload> slice(Payload input, long size) { checkNotNull(input, "input"); checkArgument(size >= 0, "size must be non-negative but was: %s", size); ContentMetadata meta = BaseMutableContentMetadata.fromContentMetadata(input.getContentMetadata()) .toBuilder() .contentLength(size) .contentMD5(null) .build(); Object rawContent = input.getRawContent(); if (rawContent instanceof File) { return doSlice((File) rawContent, meta); } else if (rawContent instanceof String) { return doSlice((String) rawContent, meta); } else if (rawContent instanceof byte[]) { return doSlice((byte[]) rawContent, meta); } else if (rawContent instanceof InputStream) { return doSlice((InputStream) rawContent, meta); } else { return doSlice(input, meta); } }
Source:
<code><START> protected Boolean getInvalidConfiguration() { <END> return invalidConfiguration; }</code><technical_language>boolean</technical_language>

Target:
protected boolean getInvalidConfiguration() { return invalidConfiguration; }
Source:
<code>private double[] getFilteredValues(double[] data) { int rows = (int) getRowCount(); double[] values = new double[rows]; BitSet masked = mask.getMaskedRows(this); int c = 0; for (int i=0; i<(int) plotterTable.getRowCount(); i++) { if (!masked.get(i)) { <START> values[c++] = data[i]; <END> } } return values; }</code><technical_language>data empty length plotterTable? if so, add a check for it</technical_language>

Target:
private double[] getFilteredValues(double[] data) { int rows = (int) getRowCount(); double[] values = new double[rows]; BitSet masked = mask.getMaskedRows(this); int c = 0; for (int i=0; i<(int) plotterDataTable.getRowCount(); i++) { if (!masked.get(i)) { values[c++] = data[i]; } } return values; }
Source:
<code>void addPreference(String userID, String productID, float score) { <START> reviewCount++; <END> if (!userIDs.containsKey(userID)) userIDs.put(userID, ++userCount); if (!productIDsBi.containsKey(productID)) productIDsBi.put(productID, ++productCount); Long longUserID = userIDs.get(userID); Long longProductID = productIDsBi.get(productID); addPreferenceToUser((GenericUserPreferenceArray) usersPreferences.get(longUserID),new GenericPreference(longUserID, longProductID, score)); }</code><technical_language>This part relationship addPreference method. Try split methods</technical_language>

Target:
private void addPreference(String userID, String productID, float score) { reviewCount++; if (!userIDs.containsKey(userID)) userIDs.put(userID, ++userCount); if (!productIDsBi.containsKey(productID)) productIDsBi.put(productID, ++productCount); Long longUserID = userIDs.get(userID); Long longProductID = productIDsBi.get(productID); addPreferenceToUser((GenericUserPreferenceArray) usersPreferences.get(longUserID),new GenericPreference(longUserID, longProductID, score)); }
Source:
<code>public void initialBlockingBookieRead() throws BKException { synchronized (this) { if (initialReadonlyBookiesFuture == null && initialWritableBookiesFuture == null) { CompletableFuture<?> writable = this.registrationClient.watchWritableBookies( bookies -> processWritableBookiesChanged(bookies.getValue())); CompletableFuture<?> readonly = this.registrationClient.watchReadOnlyBookies( bookies -> processReadOnlyBookiesChanged(bookies.getValue())); <START> initialWritableBookiesFuture = writable; <END> initialReadonlyBookiesFuture = readonly; } } try { FutureUtils.result(initialWritableBookiesFuture, EXCEPTION_FUNC); } catch (BKInterruptedException ie) { Thread.currentThread().interrupt(); throw ie; } try { FutureUtils.result(initialReadonlyBookiesFuture, EXCEPTION_FUNC); } catch (BKInterruptedException ie) { Thread.currentThread().interrupt(); throw ie; } catch (Exception e) { log.error("Failed getReadOnlyBookies: ", e); } }</code><technical_language>out of curiosity - reason do "initialWritableBookiesFuture = ...watchWritableBookies"</technical_language>

Target:
public void initialBlockingBookieRead() throws BKException { CompletableFuture<?> writable; CompletableFuture<?> readonly; synchronized (this) { if (initialReadonlyBookiesFuture == null) { assert initialWritableBookiesFuture == null; writable = this.registrationClient.watchWritableBookies( bookies -> processWritableBookiesChanged(bookies.getValue())); readonly = this.registrationClient.watchReadOnlyBookies( bookies -> processReadOnlyBookiesChanged(bookies.getValue())); initialWritableBookiesFuture = writable; initialReadonlyBookiesFuture = readonly; } else { writable = initialWritableBookiesFuture; readonly = initialReadonlyBookiesFuture; } } try { FutureUtils.result(writable, EXCEPTION_FUNC); } catch (BKInterruptedException ie) { Thread.currentThread().interrupt(); throw ie; } try { FutureUtils.result(readonly, EXCEPTION_FUNC); } catch (BKInterruptedException ie) { Thread.currentThread().interrupt(); throw ie; } catch (Exception e) { log.error("Failed getReadOnlyBookies: ", e); } }
Source:
<code>private SelectionListener onAdd(Combo combo) { return new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { String selected = combo.getText(); RegistryAccountDialog dialog = new RegistryAccountDialog( getShell(), WizardMessages.getString( "ImagePullPushPage.login.title"), <START> "index.docker.io", <END> WizardMessages.getString( "RegistryAccountDialog.add.explanation")); if (dialog.open() == Window.OK) { IRegistryAccount acc = dialog.getSignonInformation(); RegistryAccountManager.getInstance().add(acc); selected = acc.getUsername() + "@" + acc.getServerAddress(); } combo.setItems(getAccountComboItems()); combo.setText(selected); } }; }</code><technical_language>I 'AbstractRegistry.DOCKERHUB_REGISTRY' changes easier track</technical_language>

Target:
private SelectionListener onAdd(Combo combo) { return new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { String selected = combo.getText(); RegistryAccountDialog dialog = new RegistryAccountDialog( getShell(), WizardMessages.getString( "ImagePullPushPage.login.title"), AbstractRegistry.DOCKERHUB_REGISTRY, WizardMessages.getString( "RegistryAccountDialog.add.explanation")); if (dialog.open() == Window.OK) { IRegistryAccount acc = dialog.getSignonInformation(); RegistryAccountManager.getInstance().add(acc); selected = acc.getUsername() + "@" + acc.getServerAddress(); } combo.setItems(getAccountComboItems()); combo.setText(selected); } }; }
Source:
<code>public Builder setChannelTimeoutMs(long timeoutMs) { <START> this.timeoutMs = timeoutMs; <END> return this; }</code><technical_language>Validation for timeout</technical_language>

Target:
public Builder setChannelTimeoutMs(long timeoutMs) { Preconditions.checkArgument(timeoutMs >= -1, "ChannelTimeoutMs has to be positive, or -1 for none."); this.timeoutMs = timeoutMs; return this; }
Source:
<code>public void testNormalizeUserName(String input, String expected) { <START> Assert.assertEquals(validator.normalizeUserName(input), expected); <END> }</code><technical_language>static methods called instance methods</technical_language>

Target:
public void testNormalizeUserName(String input, String expected) { Assert.assertEquals(normalizeUserName(input), expected); }
Source:
<code>public void evaluate_shouldReturnAllPatientsThatHaveNeverTakenListedDrugs() throws Exception { List drugSetList = new ArrayList<Concept>(); drugSetList.add(new Concept(88)); drugSetList.add(new Concept(792)); cohortDefinition.setDrugSets(drugSetList); cohortDefinition.setWhich("NONE"); Cohort cohort = Context.getService(CohortDefinitionService.class).evaluate(cohortDefinition, null); <START> System.out.println("Taking Drugs None" + cohort.getMemberIds() + " " + cohortDefinition + "==="); <END> Assert.assertTrue(cohort.contains(21)); Assert.assertTrue(cohort.contains(22)); Assert.assertEquals(2, cohort.size()); }</code><technical_language>a this? <LINK_0></technical_language>

Target:
public void evaluate_shouldReturnAllPatientsThatHaveNeverTakenListedDrugs() throws Exception { List drugSetList = new ArrayList<Concept>(); drugSetList.add(new Concept(88)); drugSetList.add(new Concept(792)); cohortDefinition.setDrugSets(drugSetList); cohortDefinition.setWhich("NONE"); Cohort cohort = Context.getService(CohortDefinitionService.class).evaluate(cohortDefinition, null); Assert.assertTrue(cohort.contains(8)); Assert.assertTrue(cohort.contains(21)); Assert.assertTrue(cohort.contains(22)); Assert.assertEquals(3, cohort.size()); }
Source:
<code>public boolean equals(Object o) { if (o instanceof MITrigger) { MITrigger other = (MITrigger) o; <START> return (null != value) ? value.equals(other.value) : null == other.value; <END> } return false; }</code><technical_language>Objects.equals too, more trend models</technical_language>

Target:
public boolean equals(Object o) { if (o instanceof MITrigger) { MITrigger other = (MITrigger) o; return Objects.equals(value, other.value); } return false; }
Source:
<code>private MethodSpec createNewBindToTargetMethod() { MethodSpec.Builder result = MethodSpec.methodBuilder(BIND_TO_TARGET) .addModifiers(PROTECTED, STATIC); if (hasMethodBindings()) { result.addParameter(targetTypeName, "target", FINAL); } else { result.addParameter(targetTypeName, "target"); } if (bindNeedsFinder()) { <START> if (hasMethodBindings()) { <END> result.addParameter(FINDER, "finder", FINAL); } else { result.addParameter(FINDER, "finder"); } result.addParameter(Object.class, "source"); } if (bindNeedsResources()) { result.addParameter(RESOURCES, "res"); } if (bindNeedsTheme()) { result.addParameter(THEME, "theme"); } if (bindNeedsUnbinder()) { result.addParameter(getHierarchyUnbinder(), "unbinder"); } generateBindViewBody(result); return result.build(); }</code><technical_language>this more exact final needed anonymous class</technical_language>

Target:
private MethodSpec createNewBindToTargetMethod() { MethodSpec.Builder result = MethodSpec.methodBuilder(BIND_TO_TARGET) .addModifiers(PROTECTED, STATIC); if (hasMethodBindings()) { result.addParameter(targetTypeName, "target", FINAL); } else { result.addParameter(targetTypeName, "target"); } if (bindNeedsFinder()) { result.addParameter(FINDER, "finder") .addParameter(Object.class, "source"); } if (bindNeedsResources()) { result.addParameter(RESOURCES, "res"); } if (bindNeedsTheme()) { result.addParameter(THEME, "theme"); } generateBindViewBody(result); return result.build(); }
Source:
<code>public List<Field> requiredFields () { <START> return Arrays.stream(fields) <END> .filter(field -> REQUIRED == field.requirement) .collect(Collectors.toList()); }</code><technical_language>convinced stream syntax adds methods these. if Java stream syntax concise, not. wondering, do find this stream syntax easier read than: List<Field> result = new ArrayList<>(); for (Field f : fields) if (f.requirement == REQUIRED) requiredFields.add(f); return result; ? basic difference is imperative style describes machine do, while stream style attempts more descriptive. I find stream style awkward jumble of function calls symbols, is essentially imperative</technical_language>

Target:
public List<Field> requiredFields () { List<Field> requiredFields = new ArrayList<>(); for (Field f : fields) if (f.requirement == REQUIRED) requiredFields.add(f); return requiredFields; }
Source:
<code>private static void writeTilesToBlockBuilder( Geometry geometry, int zoomLevel, BingTile tile, BlockBuilder blockBuilder) { int tileZoomLevel = tile.getZoomLevel(); <START> checkArgument(tile.getZoomLevel() <= zoomLevel); <END> Envelope tileEnvelope = tileToPolygon(tile); if (tileZoomLevel == zoomLevel) { if (!disjoint(tileEnvelope, geometry, null)) { BIGINT.writeLong(blockBuilder, tile.encode()); } return; } if (contains(geometry, tileEnvelope, null)) { int subTileCount = 1 << (zoomLevel - tileZoomLevel); int minX = subTileCount * tile.getX(); int minY = subTileCount * tile.getY(); for (int x = minX; x < minX + subTileCount; x++) { for (int y = minY; y < minY + subTileCount; y++) { BIGINT.writeLong(blockBuilder, BingTile.fromCoordinates(x, y, zoomLevel).encode()); } } return; } if (disjoint(tileEnvelope, geometry, null)) { return; } int minX = 2 * tile.getX(); int minY = 2 * tile.getY(); int nextZoomLevel = tileZoomLevel + 1; verify(nextZoomLevel <= MAX_ZOOM_LEVEL); for (int x = minX; x < minX + 2; x++) { for (int y = minY; y < minY + 2; y++) { writeTilesToBlockBuilder( geometry, zoomLevel, BingTile.fromCoordinates(x, y, nextZoomLevel), blockBuilder); } } }</code><technical_language>s/tile.getZoomLevel()/tileZoomLevel</technical_language>

Target:
private static void writeTilesToBlockBuilder( Geometry geometry, int zoomLevel, BingTile tile, BlockBuilder blockBuilder) { int tileZoomLevel = tile.getZoomLevel(); checkArgument(tileZoomLevel <= zoomLevel); Envelope tileEnvelope = tileToEnvelope(tile); if (tileZoomLevel == zoomLevel) { if (!disjoint(tileEnvelope, geometry, null)) { BIGINT.writeLong(blockBuilder, tile.encode()); } return; } if (contains(geometry, tileEnvelope, null)) { int subTileCount = 1 << (zoomLevel - tileZoomLevel); int minX = subTileCount * tile.getX(); int minY = subTileCount * tile.getY(); for (int x = minX; x < minX + subTileCount; x++) { for (int y = minY; y < minY + subTileCount; y++) { BIGINT.writeLong(blockBuilder, BingTile.fromCoordinates(x, y, zoomLevel).encode()); } } return; } if (disjoint(tileEnvelope, geometry, null)) { return; } int minX = 2 * tile.getX(); int minY = 2 * tile.getY(); int nextZoomLevel = tileZoomLevel + 1; verify(nextZoomLevel <= MAX_ZOOM_LEVEL); for (int x = minX; x < minX + 2; x++) { for (int y = minY; y < minY + 2; y++) { writeTilesToBlockBuilder( geometry, zoomLevel, BingTile.fromCoordinates(x, y, nextZoomLevel), blockBuilder); } } }
Source:
<code>public abstract void assertion(T actual) throws AssertionError; @Override public void describeTo(Description description) { if (lastError != null) { description.appendText("AssertionError with message: "); description.appendText(lastError.getMessage()); <START> description.appendText("\n\nStacktrace was: "); <END> description.appendText(Throwables.getStackTrace(lastError)); } }</code><technical_language>Prefer String.format("%n%nStacktrace was: ") OS agnostic</technical_language>

Target:
public abstract void assertion(T actual) throws AssertionError; @Override public void describeTo(Description description) { if (lastError != null) { description.appendText("AssertionError with message: "); description.appendText(lastError.getMessage()); description.appendText(String.format("%n%nStacktrace was: ")); description.appendText(Throwables.getStackTrace(lastError)); } }
Source:
<code>public String toString() { String effectiveSql = sqlStringBuilder.toString(); int parameterIndex = parameters.size(); while (parameterIndex > 0) { int lastQIndex = effectiveSql.lastIndexOf("?"); Object parameter = parameters.get(parameterIndex - 1); String parameterSql = parameter instanceof String ? "'" + parameter.toString() + "'" : parameter.toString(); <START> effectiveSql = effectiveSql.substring(0, lastQIndex) + parameterSql + effectiveSql.substring(lastQIndex + 1); <END> --parameterIndex; } return effectiveSql; }</code><technical_language>This loop is building a new full SQL string iteration. I recommend some other alternative operate string more efficiently (like a StringBuilder, creating intermediate string replaces question marks placeholders processed String.format() a similar substitution method)</technical_language>

Target:
public String toString() { String effectiveSql = sqlStringBuilder.toString(); for (Object parameter : parameters) { effectiveSql = effectiveSql.replaceFirst("\\?", parameter instanceof Integer ? ("%d") : "'%s'"); } return String.format(effectiveSql, parameters.toArray()); }
Source:
<code>public static PreparedStatement prepareTableSelectStatement(Connection c, String storageKey, String[] fields, String[] values, Persistable p) { org.commcare.modern.database.TableBuilder mTableBuilder = new org.commcare.modern.database.TableBuilder(storageKey); mTableBuilder.addData(p); Pair<String, String[]> mPair = DatabaseHelper.createWhere(fields, values, p); try { String queryString = <START> "SELECT * FROM " + storageKey + " WHERE " + mPair.first + ";"; <END> PreparedStatement preparedStatement = c.prepareStatement(queryString); for (int i = 0; i < mPair.second.length; i++) { preparedStatement.setString(i + 1, mPair.second[i]); } return preparedStatement; } catch (SQLException e) { e.printStackTrace(); return null; } }</code><technical_language>vulnerable injection here. SQL arguments pass values over, construct a string manually</technical_language>

Target:
public static PreparedStatement prepareTableSelectStatement(Connection c, String storageKey, String[] fields, String[] values, Persistable p) { org.commcare.modern.database.TableBuilder mTableBuilder = new org.commcare.modern.database.TableBuilder(storageKey); mTableBuilder.addData(p); Pair<String, String[]> mPair = DatabaseHelper.createWhere(fields, values, p); try { String queryString = "SELECT * FROM " + storageKey + " WHERE " + mPair.first + ";"; PreparedStatement preparedStatement = c.prepareStatement(queryString); for (int i = 0; i < mPair.second.length; i++) { preparedStatement.setString(i + 1, mPair.second[i]); } return preparedStatement; } catch (SQLException e) { throw new RuntimeException(e); } }
Source:
<code>public void start(BundleContext context) throws Exception { <START> if ("true".equalsIgnoreCase(context.getProperty(OSGI_LOADING))) { <END> LOGGER.info("Detected OSGi Environment (core is in bundle: " + context.getBundle() + "): OSGi Based Service Loading Enabled Via System/Framework Property"); SafeOsgi.OSGI = true; CORE_BUNDLE = context; } else { LOGGER.info("Detected OSGi Environment (core is in bundle: " + context.getBundle() + "): Using JDK Service Loading - Extensions Outside This Bundle Will Not Be Detected"); LOGGER.debug("JDK Service Loading Sees:\n\t" + stream(spliterator(ClassLoading.servicesOfType(ServiceFactory.class).iterator(), Long.MAX_VALUE, 0), false) .map(sf -> sf.getServiceType().getName()).collect(joining("\n\t"))); } }</code><technical_language>wondering default for this. easy is set for in OSGi? is want OSGi service loader instead of normal one</technical_language>

Target:
public void start(BundleContext context) throws Exception { BundleContext currentContext = CORE_BUNDLE.getAndUpdate(current -> current == null ? context : current); if (currentContext == null) { String greeting = "Detected OSGi Environment (core is in bundle: " + context.getBundle() + ")"; if ("false".equalsIgnoreCase(context.getProperty(OSGI_LOADING))) { SafeOsgi.disableOSGiServiceLoading(); LOGGER.info(greeting + ": OSGi Based Service Loading Disabled Via System/Framework Property - Extensions Outside This Bundle Will Not Be Detected"); LOGGER.debug("JDK Service Loading Sees:\n\t" + stream(spliterator(ClassLoading.servicesOfType(ServiceFactory.class).iterator(), Long.MAX_VALUE, 0), false) .map(sf -> sf.getServiceType().getName()).collect(joining("\n\t"))); } else { SafeOsgi.enableOSGiServiceLoading(); LOGGER.info(greeting + ": Using OSGi Based Service Loading"); } } else { throw new IllegalStateException("Multiple bundle instances running against the same core classes: existing bundle: " + currentContext.getBundle() + " new bundle: " + context.getBundle()); } }
Source:
<code>private static boolean checkForValidityOfAttributes(ArrayList<String> attributeList) { for (String str : attributeList) { <START> if (str == "-1") { <END> return false; } } return true; }</code><technical_language>== tests for reference equality, error-prone -- .equals() method..</technical_language>

Target:
private static boolean checkForValidityOfAttributes(ArrayList<String> attributeList) { for (String str : attributeList) { if (str.equals("-1")) { return false; } } return true; }
Source:
<code>public boolean hasNext() { <START> if (this.peek != null) { <END> return true; } if (!this.iterator.hasNext()) { this.iterator = this.iterable.iterator(); } return this.iterator.hasNext(); }</code><technical_language>change logic answer is true</technical_language>

Target:
public boolean hasNext() { return true; }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FlakeIdGeneratorConfig that = (FlakeIdGeneratorConfig) o; return prefetchCount == that.prefetchCount && prefetchValidityMillis == that.prefetchValidityMillis && epochStart == that.epochStart && idOffset == that.idOffset && nodeIdOffset == that.nodeIdOffset && bitsTimestamp == that.bitsTimestamp && bitsSequence == that.bitsSequence && bitsNodeId == that.bitsNodeId && allowedFutureMillis == that.allowedFutureMillis <START> && (Objects.equals(name, that.name)) <END> && statisticsEnabled == that.statisticsEnabled; }</code><technical_language>Unnecessary parenthesis</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FlakeIdGeneratorConfig that = (FlakeIdGeneratorConfig) o; return prefetchCount == that.prefetchCount && prefetchValidityMillis == that.prefetchValidityMillis && epochStart == that.epochStart && nodeIdOffset == that.nodeIdOffset && bitsSequence == that.bitsSequence && bitsNodeId == that.bitsNodeId && allowedFutureMillis == that.allowedFutureMillis && Objects.equals(name, that.name) && statisticsEnabled == that.statisticsEnabled; }
Source:
<code>public void addTriggerChangeListener(TriggerChangeListener listener) { if (listeners == null) { <START> listeners = new CopyOnWriteArraySet<TriggerChangeListener>(); <END> } listeners.add(listener); }</code><technical_language>is synchronized this lead race conditions a listener registration get lost. If simply instantiate is declared above, this happen anymore</technical_language>

Target:
public void addTriggerChangeListener(TriggerChangeListener listener) { listeners.add(listener); }
Source:
<code>public void testStartingWithoutTransport() { MockServerConfigurationBuilder b = new MockServerConfigurationBuilder(); b.startTransport(false); MockProtocolServer server = new MockProtocolServer(); try { server.start(b.build(), new DefaultCacheManager()); <START> Assert.assertFalse(server.isTransportEnabled()); <END> } finally { server.stop(); } }</code><technical_language>Calling mock methods asserting mock is weird, a "mock" assert tested component interacts in a mocked components. a name TestProtocolServer</technical_language>

Target:
public void testStartingWithoutTransport() { MockServerConfigurationBuilder b = new MockServerConfigurationBuilder(); b.startTransport(false); AbstractProtocolServer server = new MockProtocolServer(); try { server.start(b.build(), new DefaultCacheManager()); Assert.assertFalse(server.isTransportEnabled()); } finally { server.stop(); } }
Source:
<code>private void configureHateoasObjectMapper(ObjectMapper mapper, boolean indentJson) { mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); if (indentJson) { mapper.configure(SerializationFeature.INDENT_OUTPUT, true); } SimpleFilterProvider filterProvider = new SimpleFilterProvider(); filterProvider = filterProvider.addFilter("DTOFilter", new DynamicPropertyFilter()); <START> filterProvider = filterProvider.addFilter("OldDTOFilter", new DynamicPropertyFilter()); <END> filterProvider = filterProvider.addFilter("ConsumerFilter", new MultiFilter(new HateoasBeanPropertyFilter(), new DynamicPropertyFilter())); filterProvider = filterProvider.addFilter("EntitlementFilter", new MultiFilter(new HateoasBeanPropertyFilter(), new DynamicPropertyFilter())); filterProvider = filterProvider.addFilter("OwnerFilter", new MultiFilter(new HateoasBeanPropertyFilter(), new DynamicPropertyFilter())); filterProvider = filterProvider.addFilter("GuestFilter", new MultiFilter(new HateoasBeanPropertyFilter(), new DynamicPropertyFilter())); filterProvider.setDefaultFilter(new DynamicPropertyFilter()); filterProvider.setFailOnUnknownId(false); mapper.setFilterProvider(filterProvider); addMixInAnnotationsForDTOs(mapper); AnnotationIntrospector primary = new JacksonAnnotationIntrospector(); AnnotationIntrospector secondary = new JaxbAnnotationIntrospector(mapper.getTypeFactory()); AnnotationIntrospector pair = new AnnotationIntrospectorPair(primary, secondary); mapper.setAnnotationIntrospector(pair); }</code><technical_language>This is lowest priority requested, call this LegacyDTOFilter Old? I why, "old" feels rough me</technical_language>

Target:
private void configureHateoasObjectMapper(ObjectMapper mapper, boolean indentJson) { mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); if (indentJson) { mapper.configure(SerializationFeature.INDENT_OUTPUT, true); } SimpleFilterProvider filterProvider = new SimpleFilterProvider(); filterProvider = filterProvider.addFilter("DTOFilter", new DynamicPropertyFilter()); filterProvider = filterProvider.addFilter("LegacyDTOFilter", new DynamicPropertyFilter()); filterProvider = filterProvider.addFilter("ConsumerFilter", new MultiFilter(new HateoasBeanPropertyFilter(), new DynamicPropertyFilter())); filterProvider = filterProvider.addFilter("EntitlementFilter", new MultiFilter(new HateoasBeanPropertyFilter(), new DynamicPropertyFilter())); filterProvider = filterProvider.addFilter("OwnerFilter", new MultiFilter(new HateoasBeanPropertyFilter(), new DynamicPropertyFilter())); filterProvider = filterProvider.addFilter("GuestFilter", new MultiFilter(new HateoasBeanPropertyFilter(), new DynamicPropertyFilter())); filterProvider.setDefaultFilter(new DynamicPropertyFilter()); filterProvider.setFailOnUnknownId(false); mapper.setFilterProvider(filterProvider); addMixInAnnotationsForDTOs(mapper); AnnotationIntrospector primary = new JacksonAnnotationIntrospector(); AnnotationIntrospector secondary = new JaxbAnnotationIntrospector(mapper.getTypeFactory()); AnnotationIntrospector pair = new AnnotationIntrospectorPair(primary, secondary); mapper.setAnnotationIntrospector(pair); }
Source:
<code>public ExtendedQueryResult<T> orderAsc(String attribute, boolean appendEntityName) { lastPaginatedQuery = null; <START> if (!context.getRepositoryMethod().isQuery()) { <END> context.addCriteriaBuilderPostProcessor(new OrderByCriteriaBuilderPostProcessor(attribute, OrderDirection.ASC)); } else { context.addQueryStringPostProcessor(new OrderByQueryStringPostProcessor(attribute, OrderDirection.ASC, appendEntityName)); } return this; }</code><technical_language>negative logic</technical_language>

Target:
public ExtendedQueryResult<T> orderAsc(String attribute, boolean appendEntityName) { lastPaginatedQuery = null; if (context.getRepositoryMethod().isQuery()) { context.addQueryStringPostProcessor(new OrderByQueryStringPostProcessor(attribute, OrderDirection.ASC, appendEntityName)); } else { context.addCriteriaBuilderPostProcessor(new OrderByCriteriaBuilderPostProcessor(attribute, OrderDirection.ASC)); } return this; }
Source:
<code>public void createIndices(final DBCollection coll){ BasicDBObject doc = new BasicDBObject(); doc.put(SUBJECT_HASH, 1); doc.put(PREDICATE_HASH, 1); coll.createIndex(doc); doc = new BasicDBObject(PREDICATE_HASH, 1); doc.put(OBJECT_HASH, 1); doc.put(OBJECT_TYPE, 1); coll.createIndex(doc); doc = new BasicDBObject(OBJECT_HASH, 1); doc.put(OBJECT_TYPE, 1); <START> doc.put(SUBJECT, 1); <END> coll.createIndex(doc); }</code><technical_language>SUBJECT_HASH</technical_language>

Target:
public void createIndices(final DBCollection coll){ BasicDBObject doc = new BasicDBObject(); doc.put(SUBJECT_HASH, 1); doc.put(PREDICATE_HASH, 1); doc.put(OBJECT_HASH, 1); doc.put(OBJECT_TYPE, 1); coll.createIndex(doc); doc = new BasicDBObject(PREDICATE_HASH, 1); doc.put(OBJECT_HASH, 1); doc.put(OBJECT_TYPE, 1); coll.createIndex(doc); doc = new BasicDBObject(OBJECT_HASH, 1); doc.put(OBJECT_TYPE, 1); doc.put(SUBJECT_HASH, 1); coll.createIndex(doc); }
Source:
<code>public void assignAccessPoints() throws Exception { Venue venue = new Venue(new VenueGroup("group"), new VenueType("type"), Lists.newArrayList(new VenueName("info", new Language("en")))); Object apID1 = accessPointRepository.create(new NewAccessPoint(new ID("operID1"), "8.8.8.8", new MacAddress("aa:bb:cc"), "33:22:11", "model1", venue)); Object apID2 = accessPointRepository.create(new NewAccessPoint(new ID("operID1"), "9.9.9.9", new MacAddress("cc:bb:aa"), "11:22:33", "model2", venue)); <START> Object operID = operRepository.create(newOperator().build()); <END> List<ID> apIDs = Lists.newArrayList(new ID(apID1), new ID(apID2)); operRepository.assignAccessPoints(new ID(operID), apIDs); List<AccessPoint> got = operRepository.findAccessPoints(new ID(operID)); List<AccessPoint> want = Lists.newArrayList( new AccessPoint(new ID(apID1), "8.8.8.8", new MacAddress("aa:bb:cc"), "33:22:11", "model1", venue), new AccessPoint(new ID(apID2), "9.9.9.9", new MacAddress("cc:bb:aa"), "11:22:33", "model2", venue) ); assertThat(got, deepEquals(want)); }</code><technical_language>in variable</technical_language>

Target:
public void assignAccessPoints() throws Exception { NewOperator operator = newOperator().build(); Object operID = operRepository.create(operator); Venue venue = new Venue(new VenueGroup("group"), new VenueType("type"), Lists.newArrayList(new VenueName("info", new Language("en")))); Object apID1 = accessPointRepository.create(new NewAccessPoint(new ID(operID), "8.8.8.8", new MacAddress("aa:bb:cc"), "33:22:11", "model1", venue)); Object apID2 = accessPointRepository.create(new NewAccessPoint(new ID(operID), "9.9.9.9", new MacAddress("cc:bb:aa"), "11:22:33", "model2", venue)); List<ID> apIDs = Lists.newArrayList(new ID(apID1), new ID(apID2)); operRepository.assignAccessPoints(new ID(operID), apIDs); List<AccessPoint> got = operRepository.findAccessPoints(new ID(operID)); List<AccessPoint> want = Lists.newArrayList( new AccessPoint(new ID(apID1), "8.8.8.8", new MacAddress("aa:bb:cc"), "33:22:11", "model1", venue), new AccessPoint(new ID(apID2), "9.9.9.9", new MacAddress("cc:bb:aa"), "11:22:33", "model2", venue) ); assertThat(got, deepEquals(want)); }
Source:
<code>private Map<String, ActionInfo> toActionMap(RevisionResource rsrc) { Map<String, ActionInfo> out = new LinkedHashMap<>(); if (!rsrc.getControl().getCurrentUser().isIdentifiedUser()) { return out; } <START> if (!rsrc.getPatchSet().getId().equals( rsrc.getChange().currentPatchSetId())) { return out; } <END> Provider<CurrentUser> userProvider = Providers.of( rsrc.getControl().getCurrentUser()); for (UiAction.Description d : UiActions.from( revisions, rsrc, userProvider)) { out.put(d.getId(), new ActionInfo(d)); } return out; }</code><technical_language>wrong place for this kind of filtering. question if action visible for current revisions depends action is global for actions GET actions endpoint provides rendered here. right place for this filtering is Action.getDescription() method (per Action class) setVisible() setEnabled() set action description for revision. This change broke DeleteDraftPatchSet action in core: dropped this action for non-current patch sets, offered. this change broke plugins, relies fact exposed revision actions offered for non-current revisions</technical_language>

Target:
private Map<String, ActionInfo> toActionMap(RevisionResource rsrc) { Map<String, ActionInfo> out = new LinkedHashMap<>(); if (rsrc.getControl().getCurrentUser().isIdentifiedUser()) { Provider<CurrentUser> userProvider = Providers.of( rsrc.getControl().getCurrentUser()); for (UiAction.Description d : UiActions.from( revisions, rsrc, userProvider)) { out.put(d.getId(), new ActionInfo(d)); } } return out; }
Source:
<code><START> public long getSegmentsNeeded() { <END> return segmentsNeeded; }</code><technical_language>need public (same other functions)</technical_language>

Target:
long getSegmentsNeeded() { return segmentsNeeded; }
Source:
<code><START> private String emptyIfNull(Object value) { <END> return value == null ? "" : value.toString(); }</code><technical_language>I put Object return value..</technical_language>

Target:
private Object emptyIfNull(Object value) { return value == null ? "" : value; }
Source:
<code>private long moveAwayToLookLikeOldBranchedDirectory() throws IOException { File dir = directory.directory(); long timestamp = System.currentTimeMillis(); File branchDir = new File( dir, "branched-" + timestamp ); assertTrue( "create directory: " + branchDir, branchDir.mkdirs() ); for ( File file : Objects.requireNonNull( dir.listFiles() ) ) { String fileName = file.getName(); <START> if ( !fileName.equals( "debug.log" ) && !file.getName().startsWith( "branched-" ) ) <END> { FileUtils.renameFile( file, new File( branchDir, file.getName() ) ); } } return timestamp; }</code><technical_language>GraphDatabaseInternalLogIT.INTERNAL_LOG_FILE</technical_language>

Target:
private long moveAwayToLookLikeOldBranchedDirectory() throws IOException { File dir = directory.directory(); long timestamp = System.currentTimeMillis(); File branchDir = new File( dir, "branched-" + timestamp ); assertTrue( "create directory: " + branchDir, branchDir.mkdirs() ); for ( File file : Objects.requireNonNull( dir.listFiles() ) ) { String fileName = file.getName(); if ( !fileName.equals( INTERNAL_LOG_FILE ) && !file.getName().startsWith( "branched-" ) ) { FileUtils.renameFile( file, new File( branchDir, file.getName() ) ); } } return timestamp; }
Source:
<code>private static Class<?> getCollectionParameterType(MethodParameter methodParam) { Class<?> paramType = methodParam.getNestedParameterType(); if (Collection.class == paramType || List.class.isAssignableFrom(paramType)){ <START> return ResolvableType.forMethodParameter(methodParam).asCollection().resolveGeneric(); <END> } return null; }</code><technical_language>proposed changed is technically correct, please revert this for sake of readability</technical_language>

Target:
private static Class<?> getCollectionParameterType(MethodParameter methodParam) { Class<?> paramType = methodParam.getNestedParameterType(); if (Collection.class == paramType || List.class.isAssignableFrom(paramType)){ Class<?> valueType = ResolvableType.forMethodParameter(methodParam).asCollection().resolveGeneric(); if (valueType != null) { return valueType; } } return null; }
Source:
<code>protected void validateSettings(final NodeSettingsRO settings) throws InvalidSettingsException { SettingsModelString tmp_filename = m_directory_name .createCloneWithValidatedValue(settings); if (tmp_filename == null || tmp_filename.equals("")) { <START> throw new InvalidSettingsException("No Files selected."); <END> } }</code><technical_language>change mentions of files directory everywhere</technical_language>

Target:
protected void validateSettings(final NodeSettingsRO settings) throws InvalidSettingsException { SettingsModelString tmp_directoryname = m_directory_name .createCloneWithValidatedValue(settings); if (tmp_directoryname == null || tmp_directoryname.equals("")) { throw new InvalidSettingsException("No Directory selected."); } }
Source:
<code>public Response add(Disk disk) { validateParameters(disk, "format", "interface"); <START> if (!disk.isSetLunStorage()) { END> validateParameters(disk, "provisionedSize|size"); } validateEnums(Disk.class, disk); AddDiskParameters params = new AddDiskParameters(); params.setDiskInfo(getMapper(Disk.class, org.ovirt.engine.core.common.businessentities.Disk.class).map(disk, null)); if (disk.isSetStorageDomains() && disk.getStorageDomains().isSetStorageDomains() && disk.getStorageDomains().getStorageDomains().get(0).isSetId()) { params.setStorageDomainId(Guid.createGuidFromString(disk.getStorageDomains().getStorageDomains().get(0).getId())); } else if (disk.isSetStorageDomains() && disk.getStorageDomains().getStorageDomains().get(0).isSetName()) { Guid storageDomainId = getStorageDomainId(disk.getStorageDomains().getStorageDomains().get(0).getName()); if (storageDomainId == null) { notFound(StorageDomain.class); } else { params.setStorageDomainId(storageDomainId); } } return performCreation(VdcActionType.AddDisk, params, new QueryIdResolver(VdcQueryType.GetDiskByDiskId, GetDiskByDiskIdParameters.class)); }</code><technical_language>check luns list empty</technical_language>

Target:
public Response add(Disk disk) { validateParameters(disk, "format", "interface"); if (!disk.isSetLunStorage() || disk.getLunStorage().getLogicalUnits().isEmpty()) { validateParameters(disk, "provisionedSize|size"); } validateEnums(Disk.class, disk); AddDiskParameters params = new AddDiskParameters(); params.setDiskInfo(getMapper(Disk.class, org.ovirt.engine.core.common.businessentities.Disk.class).map(disk, null)); if (disk.isSetStorageDomains() && disk.getStorageDomains().isSetStorageDomains() && disk.getStorageDomains().getStorageDomains().get(0).isSetId()) { params.setStorageDomainId(Guid.createGuidFromString(disk.getStorageDomains().getStorageDomains().get(0).getId())); } else if (disk.isSetStorageDomains() && disk.getStorageDomains().getStorageDomains().get(0).isSetName()) { Guid storageDomainId = getStorageDomainId(disk.getStorageDomains().getStorageDomains().get(0).getName()); if (storageDomainId == null) { notFound(StorageDomain.class); } else { params.setStorageDomainId(storageDomainId); } } return performCreation(VdcActionType.AddDisk, params, new QueryIdResolver(VdcQueryType.GetDiskByDiskId, GetDiskByDiskIdParameters.class)); }
Source:
<code>private void appendToLog(long size) throws IOException { byte[] bytes = TestUtils.getRandomBytes((int) size); <START> bytes[random.nextInt((int) size)] = 1; <END> ByteBuffer buffer = ByteBuffer.wrap(bytes); ReadableByteChannel channel = Channels.newChannel(new ByteBufferInputStream(buffer)); log.appendFrom(channel, buffer.capacity()); }</code><technical_language>if this byte is before/after hard delete range blob? Hard delete starts a zero index blob ends end of blob. need is written range hard deleted</technical_language>

Target:
private void appendToLog(long size) throws IOException { byte[] bytes = TestUtils.getRandomBytes((int) size); if (size > HARD_DELETE_START_OFFSET) { int randomByte = (int) (HARD_DELETE_START_OFFSET + TestUtils.RANDOM.nextInt( (int) (size - HARD_DELETE_START_OFFSET - HARD_DELETE_LAST_PART_SIZE))); bytes[randomByte] = 1; } ByteBuffer buffer = ByteBuffer.wrap(bytes); ReadableByteChannel channel = Channels.newChannel(new ByteBufferInputStream(buffer)); log.appendFrom(channel, buffer.capacity()); }
Source:
<code>private void close() { try { closeExecutors(); <START> m_loader.close(); <END> if (m_client != null) { m_client.close(); m_client = null; } } catch (Exception ex) { } }</code><technical_language>loader checked if non-null if similar paradigm client. This call close() main()'s exception block -> case initialize fails in initializing loader for some reason logic initialized client connection closed is leaked</technical_language>

Target:
private void close() { try { closeExecutors(); if (m_loader != null) { m_loader.close(); m_loader = null; } if (m_client != null) { m_client.close(); m_client = null; } } catch (Exception ex) { } }
Source:
<code>public void start() { if (getBoolean(IGNITE_JVM_PAUSE_DETECTOR_DISABLED, DEFAULT_JVM_PAUSE_DETECTOR_DISABLED)) { if (log.isDebugEnabled()) log.debug("JVM Pause Detector is disabled."); return; } <START> lastWakeUpTime = System.currentTimeMillis(); <END> final Thread worker = new Thread("jvm-pause-detector-worker") { @Override public void run() { if (log.isDebugEnabled()) log.debug(getName() + " has been started."); while (true) { try { Thread.sleep(PRECISION); final long now = System.currentTimeMillis(); final long pause = now - PRECISION - lastWakeUpTime; if (pause >= THRESHOLD) { log.warning("Possible too long JVM pause: " + pause + " milliseconds."); synchronized (LongJVMPauseDetector.this) { final int next = (int)(longPausesCnt % EVT_CNT); longPausesCnt++; longPausesTotalDuration += pause; longPausesTimestamps[next] = now; longPausesDurations[next] = pause; lastWakeUpTime = now; } } else { synchronized (LongJVMPauseDetector.this) { lastWakeUpTime = now; } } } catch (InterruptedException e) { if (workerRef.compareAndSet(this, null)) log.error(getName() + " has been interrupted.", e); else if (log.isDebugEnabled()) log.debug(getName() + " has been stopped."); break; } } } }; if (!workerRef.compareAndSet(null, worker)) { log.warning(LongJVMPauseDetector.class.getSimpleName() + " already started!"); return; } worker.setDaemon(true); worker.start(); if (log.isDebugEnabled()) log.debug("LongJVMPauseDetector was successfully started"); }</code><technical_language>u initialize of new Thread("jvm-pause-detector-worker") scope</technical_language>

Target:
public void start() { if (DISABLED) { if (log.isDebugEnabled()) log.debug("JVM Pause Detector is disabled."); return; } final Thread worker = new Thread("jvm-pause-detector-worker") { @Override public void run() { synchronized (LongJVMPauseDetector.this) { lastWakeUpTime = System.currentTimeMillis(); } if (log.isDebugEnabled()) log.debug(getName() + " has been started."); while (true) { try { Thread.sleep(PRECISION); final long now = System.currentTimeMillis(); final long pause = now - PRECISION - lastWakeUpTime; if (pause >= THRESHOLD) { log.warning("Possible too long JVM pause: " + pause + " milliseconds."); synchronized (LongJVMPauseDetector.this) { final int next = (int)(longPausesCnt % EVT_CNT); longPausesCnt++; longPausesTotalDuration += pause; longPausesTimestamps[next] = now; longPausesDurations[next] = pause; lastWakeUpTime = now; } } else { synchronized (LongJVMPauseDetector.this) { lastWakeUpTime = now; } } } catch (InterruptedException e) { if (workerRef.compareAndSet(this, null)) log.error(getName() + " has been interrupted.", e); else if (log.isDebugEnabled()) log.debug(getName() + " has been stopped."); break; } } } }; if (!workerRef.compareAndSet(null, worker)) { log.warning(LongJVMPauseDetector.class.getSimpleName() + " already started!"); return; } worker.setDaemon(true); worker.start(); if (log.isDebugEnabled()) log.debug("LongJVMPauseDetector was successfully started"); }