fixed sonar rule violations

This commit is contained in:
wenshao
2012-08-29 15:36:45 +08:00
parent c96af1628e
commit 5c6d5fcadc
17 changed files with 206 additions and 211 deletions
@@ -537,7 +537,9 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
} else if (JdbcUtils.MYSQL.equals(this.dbType)) {
if (!this.isTestWhileIdle()) {
if (LOG.isWarnEnabled()) LOG.warn("Your dbType is mysql, recommend set testWhileIdle is true");
if (LOG.isWarnEnabled()) {
LOG.warn("Your dbType is mysql, recommend set testWhileIdle is true");
}
}
}
}
@@ -50,8 +50,9 @@ public class SQLBetweenExpr extends SQLExprImpl implements Serializable {
public void output(StringBuffer buf) {
this.testExpr.output(buf);
if (this.not) buf.append(" NOT BETWEEN ");
else {
if (this.not) {
buf.append(" NOT BETWEEN ");
} else {
buf.append(" BETWEEN ");
}
this.beginExpr.output(buf);
@@ -72,8 +72,9 @@ public class SQLInListExpr extends SQLExprImpl implements Serializable {
public void output(StringBuffer buf) {
this.expr.output(buf);
if (this.not) buf.append("NOT IN ");
else {
if (this.not) {
buf.append("NOT IN ");
} else {
buf.append("IN ");
}
@@ -100,9 +100,11 @@ public class SQLSelectQueryBlock extends SQLSelectQuery {
public void output(StringBuffer buf) {
buf.append("SELECT ");
if (SQLSetQuantifier.ALL == this.distionOption) buf.append("ALL ");
else if (SQLSetQuantifier.DISTINCT == this.distionOption) buf.append("DISTINCT ");
else if (SQLSetQuantifier.UNIQUE == this.distionOption) {
if (SQLSetQuantifier.ALL == this.distionOption) {
buf.append("ALL ");
} else if (SQLSetQuantifier.DISTINCT == this.distionOption) {
buf.append("DISTINCT ");
} else if (SQLSetQuantifier.UNIQUE == this.distionOption) {
buf.append("UNIQUE ");
}
@@ -170,9 +170,11 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
print(' ');
}
if (SQLSetQuantifier.ALL == x.getDistionOption()) print("ALL ");
else if (SQLSetQuantifier.DISTINCT == x.getDistionOption()) print("DISTINCT ");
else if (SQLSetQuantifier.DISTINCTROW == x.getDistionOption()) {
if (SQLSetQuantifier.ALL == x.getDistionOption()) {
print("ALL ");
} else if (SQLSetQuantifier.DISTINCT == x.getDistionOption()) {
print("DISTINCT ");
} else if (SQLSetQuantifier.DISTINCTROW == x.getDistionOption()) {
print("DISTINCTROW ");
}
@@ -495,7 +497,8 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
print("@@global.");
} else {
String varName = x.getName();
if ((!varName.startsWith("@")) && (!varName.equals("?")) && (!varName.startsWith("#")) && (!varName.startsWith("$"))) {
if ((!varName.startsWith("@")) && (!varName.equals("?")) && (!varName.startsWith("#"))
&& (!varName.startsWith("$"))) {
print("@@");
}
}
@@ -2568,7 +2571,7 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
public void endVisit(MySqlAlterTableAddIndex x) {
}
@Override
public boolean visit(MySqlAlterTableAddUnique x) {
print("ADD ");
@@ -2576,9 +2579,9 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
print(x.getType());
print(" ");
}
print("UNIQUE ");
if (x.getName() != null) {
x.getName().accept(this);
print(' ');
@@ -2586,17 +2589,17 @@ public class MySqlOutputVisitor extends SQLASTOutputVisitor implements MySqlASTV
print("(");
printAndAccept(x.getItems(), ", ");
print(")");
if (x.getUsing() != null) {
print(" USING ");
print(x.getUsing());
}
return false;
}
@Override
public void endVisit(MySqlAlterTableAddUnique x) {
}
@Override
@@ -35,8 +35,11 @@ public abstract class OracleConstraint extends OracleSQLObjectImpl {
}
public void setName(String name) {
if (name == null) this.name = null;
else this.name = new SQLIdentifierExpr(name);
if (name == null) {
this.name = null;
} else {
this.name = new SQLIdentifierExpr(name);
}
}
public void setName(SQLName name) {
@@ -30,7 +30,7 @@ public class OracleSelectQueryBlock extends SQLSelectQueryBlock {
private static final long serialVersionUID = 1L;
private final List<SQLCommentHint> hints = new ArrayList<SQLCommentHint>(1);
private final List<SQLCommentHint> hints = new ArrayList<SQLCommentHint>(1);
private OracleSelectHierachicalQueryClause hierachicalQueryClause;
private ModelClause modelClause;
@@ -93,9 +93,11 @@ public class OracleSelectQueryBlock extends SQLSelectQueryBlock {
public void output(StringBuffer buf) {
buf.append("SELECT ");
if (SQLSetQuantifier.ALL == this.distionOption) buf.append("ALL ");
else if (SQLSetQuantifier.DISTINCT == this.distionOption) buf.append("DISTINCT ");
else if (SQLSetQuantifier.UNIQUE == this.distionOption) {
if (SQLSetQuantifier.ALL == this.distionOption) {
buf.append("ALL ");
} else if (SQLSetQuantifier.DISTINCT == this.distionOption) {
buf.append("DISTINCT ");
} else if (SQLSetQuantifier.UNIQUE == this.distionOption) {
buf.append("UNIQUE ");
}
@@ -72,7 +72,7 @@ import com.alibaba.druid.sql.parser.Token;
public class OracleSelectParser extends SQLSelectParser {
public OracleSelectParser(String sql){
super (new OracleExprParser(sql));
super(new OracleExprParser(sql));
}
public OracleSelectParser(SQLExprParser exprParser){
@@ -194,8 +194,9 @@ public class OracleSelectParser extends SQLSelectParser {
if (identifierEquals("READ")) {
lexer.nextToken();
if (identifierEquals("ONLY")) lexer.nextToken();
else {
if (identifierEquals("ONLY")) {
lexer.nextToken();
} else {
throw new ParserException("syntax error");
}
@@ -203,8 +204,9 @@ public class OracleSelectParser extends SQLSelectParser {
} else if (lexer.token() == (Token.CHECK)) {
lexer.nextToken();
if (identifierEquals("OPTION")) lexer.nextToken();
else {
if (identifierEquals("OPTION")) {
lexer.nextToken();
} else {
throw new ParserException("syntax error");
}
@@ -348,7 +350,6 @@ public class OracleSelectParser extends SQLSelectParser {
model.setReturnRowsClause(returnRowsClause);
}
while (identifierEquals("REFERENCE")) {
ReferenceModelClause referenceModelClause = new ReferenceModelClause();
lexer.nextToken();
@@ -245,7 +245,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter {
for (int i = groupList.size() - 1; i >= 0; --i) {
SQLExpr item = groupList.get(i);
visitBinaryLeft(item, x.getOperator());
if (relational) {
println();
} else {
@@ -255,7 +255,6 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter {
print(" ");
}
visitorBinaryRight(x);
if (isRoot && relational) {
@@ -376,8 +375,9 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter {
}
public boolean visit(SQLExistsExpr x) {
if (x.isNot()) print("NOT EXISTS (");
else {
if (x.isNot()) {
print("NOT EXISTS (");
} else {
print("EXISTS (");
}
incrementIndent();
@@ -426,12 +426,12 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter {
public boolean visit(SQLAggregateExpr x) {
print(x.getMethodName());
print("(");
if (x.getOption() != null) {
print(x.getOption().toString());
print(' ');
}
printAndAccept(x.getArguments(), ", ");
print(")");
return false;
@@ -1123,7 +1123,7 @@ public class SQLASTOutputVisitor extends SQLASTVisitorAdapter {
print("*/");
return false;
}
@Override
public boolean visit(SQLCreateDatabaseStatement x) {
print("CREATE DATABASE ");
@@ -251,7 +251,9 @@ public final class JdbcSqlStat implements JdbcSqlStatMBean {
}
for (;;) {
long max = updateCountMax.get();
if (delta <= max) break;
if (delta <= max) {
break;
}
if (updateCountMax.compareAndSet(max, delta)) {
break;
}
@@ -307,19 +309,19 @@ public final class JdbcSqlStat implements JdbcSqlStatMBean {
public void addReadBytesLength(long length) {
this.readBytesLength.addAndGet(length);
}
public long getReaderOpenCount() {
return readerOpenCount.get();
}
public void addReaderOpenCount(int count) {
this.readerOpenCount.addAndGet(count);
}
public long getInputStreamOpenCount() {
return inputStreamOpenCount.get();
}
public void addInputStreamOpenCount(int count) {
this.inputStreamOpenCount.addAndGet(count);
}
@@ -366,7 +368,9 @@ public final class JdbcSqlStat implements JdbcSqlStatMBean {
this.fetchRowCount.addAndGet(delta);
for (;;) {
long max = fetchRowCountMax.get();
if (delta <= max) break;
if (delta <= max) {
break;
}
if (fetchRowCountMax.compareAndSet(max, delta)) {
break;
}
@@ -98,9 +98,7 @@ public class DruidStat {
try {
vm = VirtualMachine.attach(name);
} catch (AttachNotSupportedException x) {
IOException ioe = new IOException(x.getMessage());
ioe.initCause(x);
throw ioe;
throw new IOException(x.getMessage(), x);
}
String home = vm.getSystemProperties().getProperty("java.home");
@@ -122,13 +120,9 @@ public class DruidStat {
try {
vm.loadAgent(agent, "com.sun.management.jmxremote");
} catch (AgentLoadException x) {
IOException ioe = new IOException(x.getMessage());
ioe.initCause(x);
throw ioe;
throw new IOException(x.getMessage(), x);
} catch (AgentInitializationException x) {
IOException ioe = new IOException(x.getMessage());
ioe.initCause(x);
throw ioe;
throw new IOException(x.getMessage(), x);
}
// get the connector address
@@ -69,9 +69,13 @@ public class TableFormatter {
}
public static String padStr(String old, int length) {
if (old == null ) return "";
if (old == null ) {
return "";
}
int vlen = displayLen(old);
if (vlen > length) return old;
if (vlen > length) {
return old;
}
StringBuffer sb = new StringBuffer(old);
for (int i=0; i< length -vlen ; i++) {
sb.append(" ");
@@ -23,62 +23,45 @@ import com.alibaba.druid.sql.SQLUtils;
public class TabledDataPrinter {
private static final int SQL_MAX_LEN = 32;
private static final int MAX_COL = 4;
private static final String[] sqlRowTitle = new String[] {
"ID", "SQL", "ExecCount", "ExecTime",
"ExecMax","Txn", "Error","Update","FetchRow","Running","Concurrent",
"ExecHisto", "ExecRsHisto","FetchRowHisto","UpdateHisto" };
private static final String[] sqlRowField = new String[] {
"ID", "SQL", "ExecuteCount", "TotalTime", "MaxTimespan",
"InTransactionCount", "ErrorCount", "EffectedRowCount", "FetchRowCount",
"RunningCount","ConcurrentMax","Histogram","ExecuteAndResultHoldTimeHistogram",
"FetchRowCountHistogram","EffectedRowCountHistogram" };
private static final String[] sqlColField = new String[] {
"ID", "DataSource", "SQL", "ExecuteCount", "ErrorCount",
"TotalTime", "LastTime", "MaxTimespan", "LastError", "EffectedRowCount",
"FetchRowCount", "MaxTimespanOccurTime", "BatchSizeMax", "BatchSizeTotal", "ConcurrentMax",
"RunningCount", "Name", "File",
"LastErrorMessage", "LastErrorClass", "LastErrorStackTrace", "LastErrorTime",
"DbType", "URL", "InTransactionCount",
"Histogram", "LastSlowParameters", "ResultSetHoldTime", "ExecuteAndResultSetHoldTime", "FetchRowCountHistogram",
"EffectedRowCountHistogram", "ExecuteAndResultHoldTimeHistogram", "EffectedRowCountMax", "FetchRowCountMax", "ClobOpenCount" };
private static final int SQL_MAX_LEN = 32;
private static final int MAX_COL = 4;
private static final String[] sqlRowTitle = new String[] { "ID", "SQL", "ExecCount", "ExecTime", "ExecMax", "Txn",
"Error", "Update", "FetchRow", "Running", "Concurrent", "ExecHisto", "ExecRsHisto", "FetchRowHisto",
"UpdateHisto" };
private static final String[] dsRowTitle = new String[] {
"Name", "DbType",
"PoolingCount", "PoolingPeak", "PoolingPeakTime",
"ActiveCount", "ActivePeak", "ActivePeakTime",
"ExecuteCount", "ErrorCount", "CommitCount", "RollbackCount" };
private static final String[] sqlRowField = new String[] { "ID", "SQL", "ExecuteCount", "TotalTime", "MaxTimespan",
"InTransactionCount", "ErrorCount", "EffectedRowCount", "FetchRowCount", "RunningCount", "ConcurrentMax",
"Histogram", "ExecuteAndResultHoldTimeHistogram", "FetchRowCountHistogram", "EffectedRowCountHistogram" };
private static final String[] dsRowField = new String[] {
"Name", "DbType",
"PoolingCount", "PoolingPeak", "PoolingPeakTime",
"ActiveCount", "ActivePeak", "ActivePeakTime",
"ExecuteCount", "ErrorCount", "CommitCount", "RollbackCount" };
private static final String[] sqlColField = new String[] { "ID", "DataSource", "SQL", "ExecuteCount", "ErrorCount",
"TotalTime", "LastTime", "MaxTimespan", "LastError", "EffectedRowCount", "FetchRowCount",
"MaxTimespanOccurTime", "BatchSizeMax", "BatchSizeTotal", "ConcurrentMax", "RunningCount", "Name", "File",
"LastErrorMessage", "LastErrorClass", "LastErrorStackTrace", "LastErrorTime", "DbType", "URL",
"InTransactionCount", "Histogram", "LastSlowParameters", "ResultSetHoldTime",
"ExecuteAndResultSetHoldTime", "FetchRowCountHistogram", "EffectedRowCountHistogram",
"ExecuteAndResultHoldTimeHistogram", "EffectedRowCountMax", "FetchRowCountMax", "ClobOpenCount" };
private static final String[] dsRowTitle = new String[] { "Name", "DbType", "PoolingCount", "PoolingPeak",
"PoolingPeakTime", "ActiveCount", "ActivePeak", "ActivePeakTime", "ExecuteCount", "ErrorCount",
"CommitCount", "RollbackCount" };
private static final String[] dsColField = new String[] {
"Identity", "Name", "DbType", "DriverClassName", "URL", "UserName", "FilterClassNames",
"WaitThreadCount", "NotEmptyWaitCount", "NotEmptyWaitMillis",
"PoolingCount", "PoolingPeak", "PoolingPeakTime",
"ActiveCount", "ActivePeak", "ActivePeakTime",
"InitialSize", "MinIdle", "MaxActive",
"QueryTimeout", "TransactionQueryTimeout", "LoginTimeout", "ValidConnectionCheckerClassName", "ExceptionSorterClassName",
"TestOnBorrow", "TestOnReturn", "TestWhileIdle",
"DefaultAutoCommit", "DefaultReadOnly", "DefaultTransactionIsolation",
"LogicConnectCount", "LogicCloseCount", "LogicConnectErrorCount",
"PhysicalConnectCount", "PhysicalCloseCount", "PhysicalConnectErrorCount",
"ExecuteCount", "ErrorCount", "CommitCount", "RollbackCount",
"PSCacheAccessCount", "PSCacheHitCount", "PSCacheMissCount",
"StartTransactionCount", "TransactionHistogram",
"ConnectionHoldTimeHistogram", "RemoveAbandoned", "ClobOpenCount" };
private static final String[] dsRowField = new String[] { "Name", "DbType", "PoolingCount", "PoolingPeak",
"PoolingPeakTime", "ActiveCount", "ActivePeak", "ActivePeakTime", "ExecuteCount", "ErrorCount",
"CommitCount", "RollbackCount" };
public static void printActiveConnStack(List<List<String >> content,Option opt) {
private static final String[] dsColField = new String[] { "Identity", "Name", "DbType", "DriverClassName", "URL",
"UserName", "FilterClassNames", "WaitThreadCount", "NotEmptyWaitCount", "NotEmptyWaitMillis",
"PoolingCount", "PoolingPeak", "PoolingPeakTime", "ActiveCount", "ActivePeak", "ActivePeakTime",
"InitialSize", "MinIdle", "MaxActive", "QueryTimeout", "TransactionQueryTimeout", "LoginTimeout",
"ValidConnectionCheckerClassName", "ExceptionSorterClassName", "TestOnBorrow", "TestOnReturn",
"TestWhileIdle", "DefaultAutoCommit", "DefaultReadOnly", "DefaultTransactionIsolation",
"LogicConnectCount", "LogicCloseCount", "LogicConnectErrorCount", "PhysicalConnectCount",
"PhysicalCloseCount", "PhysicalConnectErrorCount", "ExecuteCount", "ErrorCount", "CommitCount",
"RollbackCount", "PSCacheAccessCount", "PSCacheHitCount", "PSCacheMissCount", "StartTransactionCount",
"TransactionHistogram", "ConnectionHoldTimeHistogram", "RemoveAbandoned", "ClobOpenCount" };
public static void printActiveConnStack(List<List<String>> content, Option opt) {
for (List<String> stack : content) {
for (String line : stack) {
System.out.println(line);
@@ -87,7 +70,7 @@ public class TabledDataPrinter {
}
}
public static void printDataSourceData(List<Map<String, Object>> content,Option opt) {
public static void printDataSourceData(List<Map<String, Object>> content, Option opt) {
if (opt.getStyle() == Option.PrintStyle.HORIZONTAL) {
System.out.println(getFormattedOutput(content, dsRowTitle, dsRowField));
} else {
@@ -96,23 +79,22 @@ public class TabledDataPrinter {
}
public static void printSqlData(List<Map<String, Object>> content, Option opt) {
if (opt.getId() != -1) {
List<Map<String,Object>> matchedContent = new ArrayList<Map<String,Object>>();
for (Map<String, Object> sqlStat : content) {
Integer idStr = (Integer)sqlStat.get("ID");
if (idStr.intValue() == opt.getId()) {
matchedContent.add(sqlStat);
String dbType = (String) sqlStat.get("DbType");
String sql = (String) sqlStat.get("SQL");
System.out.println(SQLUtils.format(sql, dbType));
System.out.println("===============================\n");
break;
}
}
content = matchedContent;
if (opt.getId() != -1) {
List<Map<String, Object>> matchedContent = new ArrayList<Map<String, Object>>();
for (Map<String, Object> sqlStat : content) {
Integer idStr = (Integer) sqlStat.get("ID");
if (idStr.intValue() == opt.getId()) {
matchedContent.add(sqlStat);
String dbType = (String) sqlStat.get("DbType");
String sql = (String) sqlStat.get("SQL");
System.out.println(SQLUtils.format(sql, dbType));
System.out.println("===============================\n");
break;
}
}
content = matchedContent;
}
}
if (opt.getStyle() == Option.PrintStyle.HORIZONTAL) {
System.out.println(getFormattedOutput(content, sqlRowTitle, sqlRowField));
} else {
@@ -120,17 +102,16 @@ public class TabledDataPrinter {
}
}
public static String getFormattedOutput(List<Map<String, Object>> content,
String[] title , String[] rowField) {
public static String getFormattedOutput(List<Map<String, Object>> content, String[] title, String[] rowField) {
List<String[]> printContents = new ArrayList<String[]>();
printContents.add(title);
for (Map<String, Object> sqlStat : content) {
String[] row = new String[rowField.length];
for (int i = 0; i < rowField.length; ++i) {
Object value = sqlStat.get(rowField[i]);
row[i] = handleAndConvert(value,rowField[i]);
row[i] = handleAndConvert(value, rowField[i]);
}
printContents.add(row);
}
@@ -138,19 +119,18 @@ public class TabledDataPrinter {
return formattedStr;
}
public static String getVerticalFormattedOutput(List<Map<String, Object>> content, String[] titleFields) {
List<String[]> printContents = new ArrayList<String[]>();
int maxCol = content.size() > MAX_COL ? MAX_COL: content.size();
int maxCol = content.size() > MAX_COL ? MAX_COL : content.size();
for (int i = 0; i < titleFields.length; ++i) {
String[] row = new String[maxCol+1];
String[] row = new String[maxCol + 1];
row[0] = titleFields[i];
for (int j=0; j< maxCol ; j++) {
Map<String,Object> sqlStat = content.get(j);
for (int j = 0; j < maxCol; j++) {
Map<String, Object> sqlStat = content.get(j);
Object value = sqlStat.get(titleFields[i]);
row[j+1] = handleAndConvert(value, titleFields[i]);
row[j + 1] = handleAndConvert(value, titleFields[i]);
}
printContents.add(row);
}
@@ -161,11 +141,11 @@ public class TabledDataPrinter {
public static String handleAndConvert(Object value, String fieldName) {
if (value == null) value = "";
if (fieldName.equals("SQL")) {
String sql = (String)value;
String sql = (String) value;
sql = sql.replace("\n", " ");
sql = sql.replace("\t", " ");
if (sql.length() > SQL_MAX_LEN) {
sql = sql.substring(0,SQL_MAX_LEN-3) + "...";
sql = sql.substring(0, SQL_MAX_LEN - 3) + "...";
}
value = sql;
}
@@ -124,7 +124,9 @@ public class Base64 {
byte[] alphaToInt = (alternate ? altBase64ToInt : base64ToInt);
int sLen = s.length();
int numGroups = sLen / 4;
if (4 * numGroups != sLen) throw new IllegalArgumentException("String length must be a multiple of four.");
if (4 * numGroups != sLen) {
throw new IllegalArgumentException("String length must be a multiple of four.");
}
int missingBytesInLastGroup = 0;
int numFullGroups = numGroups;
if (sLen != 0) {
@@ -132,7 +134,9 @@ public class Base64 {
missingBytesInLastGroup++;
numFullGroups--;
}
if (s.charAt(sLen - 2) == '=') missingBytesInLastGroup++;
if (s.charAt(sLen - 2) == '=') {
missingBytesInLastGroup++;
}
}
byte[] result = new byte[3 * numGroups - missingBytesInLastGroup];
@@ -172,7 +176,9 @@ public class Base64 {
*/
private static int base64toInt(char c, byte[] alphaToInt) {
int result = alphaToInt[c];
if (result < 0) throw new IllegalArgumentException("Illegal character " + c);
if (result < 0) {
throw new IllegalArgumentException("Illegal character " + c);
}
return result;
}
@@ -147,7 +147,9 @@ public abstract class LazyCompositeData implements CompositeData, Serializable {
Set<?> allItems = type1.keySet();
// Check all items in the type1 exist in type2
if (!type2.keySet().containsAll(allItems)) return false;
if (!type2.keySet().containsAll(allItems)) {
return false;
}
for (Iterator<?> iter = allItems.iterator(); iter.hasNext();) {
String item = (String) iter.next();
@@ -183,7 +185,9 @@ public abstract class LazyCompositeData implements CompositeData, Serializable {
List<String> list2 = type2.getIndexNames();
// check if the list of index names are the same
if (!list1.equals(list2)) return false;
if (!list1.equals(list2)) {
return false;
}
return isTypeMatched(type1.getRowType(), type2.getRowType());
}
@@ -50,7 +50,9 @@ public class MapComparator<K extends Object, V extends Object> implements Compar
public int compare(Map<K, V> o1, Map<K, V> o2) {
int result = compare_0(o1, o2);
if (isDesc) result = -result;
if (isDesc) {
result = -result;
}
return result;
}
@@ -61,7 +63,9 @@ public class MapComparator<K extends Object, V extends Object> implements Compar
if (keyStr.matches(".+\\[[0-9]+\\]")) {
Object value = map.get(keyStr.substring(0, keyStr.indexOf("[")));
if (value == null) return null;
if (value == null) {
return null;
}
Integer index = StringUtils.subStringToInteger(keyStr, "[", "]");
if (value.getClass().isArray() && Array.getLength(value) >= index) {
@@ -15,81 +15,71 @@
*/
package com.alibaba.druid.util;
import java.util.Random;
/**
* A random number generator isolated to the current thread. Like the
* global {@link java.util.Random} generator used by the {@link
* java.lang.Math} class, a {@code ThreadLocalRandom} is initialized
* with an internally generated seed that may not otherwise be
* modified. When applicable, use of {@code ThreadLocalRandom} rather
* than shared {@code Random} objects in concurrent programs will
* typically encounter much less overhead and contention. Use of
* {@code ThreadLocalRandom} is particularly appropriate when multiple
* tasks (for example, each a {@link ForkJoinTask}) use random numbers
* in parallel in thread pools.
*
* <p>Usages of this class should typically be of the form:
* {@code ThreadLocalRandom.current().nextX(...)} (where
* {@code X} is {@code Int}, {@code Long}, etc).
* When all usages are of this form, it is never possible to
* accidently share a {@code ThreadLocalRandom} across multiple threads.
*
* <p>This class also provides additional commonly used bounded random
* generation methods.
*
* A random number generator isolated to the current thread. Like the global {@link java.util.Random} generator used by
* the {@link java.lang.Math} class, a {@code ThreadLocalRandom} is initialized with an internally generated seed that
* may not otherwise be modified. When applicable, use of {@code ThreadLocalRandom} rather than shared {@code Random}
* objects in concurrent programs will typically encounter much less overhead and contention. Use of
* {@code ThreadLocalRandom} is particularly appropriate when multiple tasks (for example, each a {@link ForkJoinTask})
* use random numbers in parallel in thread pools.
* <p>
* Usages of this class should typically be of the form: {@code ThreadLocalRandom.current().nextX(...)} (where {@code X}
* is {@code Int}, {@code Long}, etc). When all usages are of this form, it is never possible to accidently share a
* {@code ThreadLocalRandom} across multiple threads.
* <p>
* This class also provides additional commonly used bounded random generation methods.
*
* @since 1.7
* @author Doug Lea
*/
public class ThreadLocalRandom extends Random {
// same constants as Random, but must be redeclared because private
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
/**
* The random seed. We can't use super.seed.
*/
private long rnd;
private long rnd;
/**
* Initialization flag to permit calls to setSeed to succeed only
* while executing the Random constructor. We can't allow others
* since it would cause setting seed in one part of a program to
* unintentionally impact other usages by the thread.
* Initialization flag to permit calls to setSeed to succeed only while executing the Random constructor. We can't
* allow others since it would cause setting seed in one part of a program to unintentionally impact other usages by
* the thread.
*/
boolean initialized;
boolean initialized;
// Padding to help avoid memory contention among seed updates in
// different TLRs in the common case that they are located near
// each other.
@SuppressWarnings("unused")
private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
/**
* The actual ThreadLocal
*/
private static final ThreadLocal<ThreadLocalRandom> localRandom =
new ThreadLocal<ThreadLocalRandom>() {
protected ThreadLocalRandom initialValue() {
return new ThreadLocalRandom();
}
};
private static final ThreadLocal<ThreadLocalRandom> localRandom = new ThreadLocal<ThreadLocalRandom>() {
protected ThreadLocalRandom initialValue() {
return new ThreadLocalRandom();
}
};
/**
* Constructor called only by localRandom.initialValue.
*/
ThreadLocalRandom() {
ThreadLocalRandom(){
super();
initialized = true;
}
/**
* Returns the current thread's {@code ThreadLocalRandom}.
*
*
* @return the current thread's {@code ThreadLocalRandom}
*/
public static ThreadLocalRandom current() {
@@ -97,9 +87,8 @@ public class ThreadLocalRandom extends Random {
}
/**
* Throws {@code UnsupportedOperationException}. Setting seeds in
* this generator is not supported.
*
* Throws {@code UnsupportedOperationException}. Setting seeds in this generator is not supported.
*
* @throws UnsupportedOperationException always
*/
public void setSeed(long seed) {
@@ -111,17 +100,16 @@ public class ThreadLocalRandom extends Random {
protected int next(int bits) {
rnd = (rnd * multiplier + addend) & mask;
return (int) (rnd >>> (48-bits));
return (int) (rnd >>> (48 - bits));
}
/**
* Returns a pseudorandom, uniformly distributed value between the
* given least value (inclusive) and bound (exclusive).
*
* Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound
* (exclusive).
*
* @param least the least value returned
* @param bound the upper bound (exclusive)
* @throws IllegalArgumentException if least greater than or equal
* to bound
* @throws IllegalArgumentException if least greater than or equal to bound
* @return the next value
*/
public int nextInt(int least, int bound) {
@@ -132,11 +120,9 @@ public class ThreadLocalRandom extends Random {
}
/**
* Returns a pseudorandom, uniformly distributed value
* between 0 (inclusive) and the specified value (exclusive).
*
* @param n the bound on the random number to be returned. Must be
* positive.
* Returns a pseudorandom, uniformly distributed value between 0 (inclusive) and the specified value (exclusive).
*
* @param n the bound on the random number to be returned. Must be positive.
* @return the next value
* @throws IllegalArgumentException if n is not positive
*/
@@ -154,22 +140,22 @@ public class ThreadLocalRandom extends Random {
int bits = next(2);
long half = n >>> 1;
long nextn = ((bits & 2) == 0) ? half : n - half;
if ((bits & 1) == 0)
if ((bits & 1) == 0) {
offset += n - nextn;
}
n = nextn;
}
return offset + nextInt((int) n);
}
/**
* Returns a pseudorandom, uniformly distributed value between the
* given least value (inclusive) and bound (exclusive).
*
* Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound
* (exclusive).
*
* @param least the least value returned
* @param bound the upper bound (exclusive)
* @return the next value
* @throws IllegalArgumentException if least greater than or equal
* to bound
* @throws IllegalArgumentException if least greater than or equal to bound
*/
public long nextLong(long least, long bound) {
if (least >= bound) {
@@ -179,11 +165,10 @@ public class ThreadLocalRandom extends Random {
}
/**
* Returns a pseudorandom, uniformly distributed {@code double} value
* between 0 (inclusive) and the specified value (exclusive).
*
* @param n the bound on the random number to be returned. Must be
* positive.
* Returns a pseudorandom, uniformly distributed {@code double} value between 0 (inclusive) and the specified value
* (exclusive).
*
* @param n the bound on the random number to be returned. Must be positive.
* @return the next value
* @throws IllegalArgumentException if n is not positive
*/
@@ -195,14 +180,13 @@ public class ThreadLocalRandom extends Random {
}
/**
* Returns a pseudorandom, uniformly distributed value between the
* given least value (inclusive) and bound (exclusive).
*
* Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound
* (exclusive).
*
* @param least the least value returned
* @param bound the upper bound (exclusive)
* @return the next value
* @throws IllegalArgumentException if least greater than or equal
* to bound
* @throws IllegalArgumentException if least greater than or equal to bound
*/
public double nextDouble(double least, double bound) {
if (least >= bound) {