Bug #77171 On every connect getting sql_mode from server creates unnecessary exception
Submitted: 27 May 2015 12:41 Modified: 21 Apr 2016 21:21
Reporter: Alexei Shpikat Email Updates:
Status: Closed Impact on me:
None 
Category:Connector / J Severity:S5 (Performance)
Version:5.1.35 OS:Any
Assigned to: Filipe Silva CPU Architecture:Any

[27 May 2015 12:41] Alexei Shpikat
Description:
When establishing a connection Connector gets "sql_mode" variable from a server and tries to parse it as a number, as it was a number in older days, but it hasn't for quite a long time, so I assume in real world the NumberFormatException is thrown in over 99% cases. And we all know that throwing an exception is a heavy operation.

How to repeat:
Source code of ConnectionImpl, starting line 3336:

                String sqlModeAsString = this.serverVariables.get("sql_mode");
                try {
                    sqlMode = Integer.parseInt(sqlModeAsString);
                } catch (NumberFormatException nfe) {
                    // newer versions of the server has this as a string-y list...
                    sqlMode = 0;

                    // ... omitting "string-y list" parsing
                }

Suggested fix:
As this should be just a really quick check (which probably will fail almost always), I suggest a simple check whether each of the string characters is a digit:

private boolean isProbablyInt(final String string) {
  for (int i = 0; i < string.length; i++) {
    final char ch = string.charAt(i);
    if (ch < '0' || ch > '9') {
      return false;
    }
  return true;
}

Condition could be changed to worse performing, but a little bit more correct (which we don't actually need here): Character.isDigit(ch)
[1 Jun 2015 22:26] Filipe Silva
Hi Alexei,

Thank you for this bug report. Verified as described.
[21 Apr 2016 21:21] Daniel So
Added the following entry to the MySQL Connector/J 5.1.39 changelog:

"At every connection, Connector/J got the sql_mode variable from the server and tried to parse it as a number; because sql_mode is not a number (except for very old versions of MySQL), an NumberFormatException was always thrown and then caught by the code. This fix refactored the code to avoid the unnecessary throwing and catching of the error."
[14 Jun 2016 19:41] Daniel So
Posted by developer:
 
Added the above-mentioned changelog entry for Connector/J 6.0.3 as well, as the fix has been pushed into the 6.0 tree.