Add assertions enabled helper

Today in the code base we have lots of ugly code blocks like:

  boolean assertionsEnabled = false;
  assert assertionsEnabled = true;
  if (assertionsEnabled) {
    // something
  }

These are a nuisance. Instead, we can do this in exactly one place and
replace these blocks with

  if (Assertions.ENABLED) {
    // something
  }

The cool thing here is that since this is a static final field, the JIT
can optimize away the check at runtime if assertions are disabled.

Relates #24834
This commit is contained in:
Jason Tedor 2017-05-23 08:22:18 -04:00 committed by GitHub
parent 747fa721e4
commit c179c6a4c9
7 changed files with 57 additions and 19 deletions

View File

@ -0,0 +1,45 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch;
/**
* Provides a static final field that can be used to check if assertions are enabled. Since this field might be used elsewhere to check if
* assertions are enabled, if you are running with assertions enabled for specific packages or classes, you should enable assertions on this
* class too (e.g., {@code -ea org.elasticsearch.Assertions -ea org.elasticsearch.cluster.service.MasterService}).
*/
public final class Assertions {
private Assertions() {
}
public static final boolean ENABLED;
static {
boolean enabled = false;
/*
* If assertions are enabled, the following line will be evaluated and enabled will have the value true, otherwise when assertions
* are disabled enabled will have the value false.
*/
assert enabled = true;
ENABLED = enabled;
}
}

View File

@ -23,6 +23,7 @@ import com.carrotsearch.hppc.ObjectIntHashMap;
import com.carrotsearch.hppc.cursors.ObjectCursor; import com.carrotsearch.hppc.cursors.ObjectCursor;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.lucene.util.CollectionUtil; import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.Assertions;
import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.metadata.MetaData;
@ -1018,9 +1019,7 @@ public class RoutingNodes implements Iterable<RoutingNode> {
* this method does nothing. * this method does nothing.
*/ */
public static boolean assertShardStats(RoutingNodes routingNodes) { public static boolean assertShardStats(RoutingNodes routingNodes) {
boolean run = false; if (!Assertions.ENABLED) {
assert (run = true); // only run if assertions are enabled!
if (!run) {
return true; return true;
} }
int unassignedPrimaryCount = 0; int unassignedPrimaryCount = 0;

View File

@ -22,6 +22,7 @@ package org.elasticsearch.cluster.service;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.Supplier; import org.apache.logging.log4j.util.Supplier;
import org.elasticsearch.Assertions;
import org.elasticsearch.cluster.AckedClusterStateTaskListener; import org.elasticsearch.cluster.AckedClusterStateTaskListener;
import org.elasticsearch.cluster.ClusterChangedEvent; import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ClusterState;
@ -666,9 +667,7 @@ public class MasterService extends AbstractLifecycleComponent {
assert clusterTasksResult.executionResults.size() == taskInputs.updateTasks.size() assert clusterTasksResult.executionResults.size() == taskInputs.updateTasks.size()
: String.format(Locale.ROOT, "expected [%d] task result%s but was [%d]", taskInputs.updateTasks.size(), : String.format(Locale.ROOT, "expected [%d] task result%s but was [%d]", taskInputs.updateTasks.size(),
taskInputs.updateTasks.size() == 1 ? "" : "s", clusterTasksResult.executionResults.size()); taskInputs.updateTasks.size() == 1 ? "" : "s", clusterTasksResult.executionResults.size());
boolean assertsEnabled = false; if (Assertions.ENABLED) {
assert (assertsEnabled = true);
if (assertsEnabled) {
ClusterTasksResult<Object> finalClusterTasksResult = clusterTasksResult; ClusterTasksResult<Object> finalClusterTasksResult = clusterTasksResult;
taskInputs.updateTasks.forEach(updateTask -> { taskInputs.updateTasks.forEach(updateTask -> {
assert finalClusterTasksResult.executionResults.containsKey(updateTask.task) : assert finalClusterTasksResult.executionResults.containsKey(updateTask.task) :

View File

@ -23,6 +23,7 @@ import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.GeometryFactory;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.elasticsearch.Assertions;
import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.action.support.ToXContentToBytes; import org.elasticsearch.action.support.ToXContentToBytes;
import org.elasticsearch.common.io.stream.NamedWriteable; import org.elasticsearch.common.io.stream.NamedWriteable;
@ -58,9 +59,7 @@ public abstract class ShapeBuilder extends ToXContentToBytes implements NamedWri
static { static {
// if asserts are enabled we run the debug statements even if they are not logged // if asserts are enabled we run the debug statements even if they are not logged
// to prevent exceptions only present if debug enabled // to prevent exceptions only present if debug enabled
boolean debug = false; DEBUG = Assertions.ENABLED;
assert debug = true;
DEBUG = debug;
} }
public static final double DATELINE = 180; public static final double DATELINE = 180;

View File

@ -21,6 +21,7 @@ package org.elasticsearch.common.lucene;
import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.LeafReader;
import org.elasticsearch.Assertions;
import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.ShardUtils; import org.elasticsearch.index.shard.ShardUtils;
@ -152,10 +153,7 @@ public final class ShardCoreKeyMap {
} }
private synchronized boolean assertSize() { private synchronized boolean assertSize() {
// this is heavy and should only used in assertions if (!Assertions.ENABLED) {
boolean assertionsEnabled = false;
assert assertionsEnabled = true;
if (assertionsEnabled == false) {
throw new AssertionError("only run this if assertions are enabled"); throw new AssertionError("only run this if assertions are enabled");
} }
Collection<Set<IndexReader.CacheKey>> values = indexToCoreKey.values(); Collection<Set<IndexReader.CacheKey>> values = indexToCoreKey.values();

View File

@ -19,6 +19,7 @@
package org.elasticsearch.common.util.concurrent; package org.elasticsearch.common.util.concurrent;
import org.elasticsearch.Assertions;
import org.elasticsearch.common.lease.Releasable; import org.elasticsearch.common.lease.Releasable;
import org.elasticsearch.index.engine.EngineException; import org.elasticsearch.index.engine.EngineException;
@ -35,9 +36,7 @@ public class ReleasableLock implements Releasable {
public ReleasableLock(Lock lock) { public ReleasableLock(Lock lock) {
this.lock = lock; this.lock = lock;
boolean useHoldingThreads = false; if (Assertions.ENABLED) {
assert (useHoldingThreads = true);
if (useHoldingThreads) {
holdingThreads = new ThreadLocal<>(); holdingThreads = new ThreadLocal<>();
} else { } else {
holdingThreads = null; holdingThreads = null;

View File

@ -19,6 +19,7 @@
package org.elasticsearch.common.hppc; package org.elasticsearch.common.hppc;
import com.carrotsearch.hppc.ObjectHashSet; import com.carrotsearch.hppc.ObjectHashSet;
import org.elasticsearch.Assertions;
import org.elasticsearch.common.collect.HppcMaps; import org.elasticsearch.common.collect.HppcMaps;
import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTestCase;
@ -29,9 +30,7 @@ import static org.hamcrest.Matchers.equalTo;
public class HppcMapsTests extends ESTestCase { public class HppcMapsTests extends ESTestCase {
public void testIntersection() throws Exception { public void testIntersection() throws Exception {
boolean enabled = false; assumeTrue("assertions enabled", Assertions.ENABLED);
assert enabled = true;
assumeTrue("assertions enabled", enabled);
ObjectHashSet<String> set1 = ObjectHashSet.from("1", "2", "3"); ObjectHashSet<String> set1 = ObjectHashSet.from("1", "2", "3");
ObjectHashSet<String> set2 = ObjectHashSet.from("1", "2", "3"); ObjectHashSet<String> set2 = ObjectHashSet.from("1", "2", "3");
List<String> values = toList(HppcMaps.intersection(set1, set2)); List<String> values = toList(HppcMaps.intersection(set1, set2));