Java JDBC doesn't use String values?

My colleague and I have memory problems with the application, and one discovery we made was that the String values ​​coming from the database (which strongly duplicate) are not actually interned. Therefore, duplicate values ​​are stored in memory, which could potentially be a huge problem.

For example, here is a simple JDBC example querying for identical rows from a SQLite database. I am printing a hash code of the identifier of each of them, and it shows that each of them is a separate instance.

import java.sql.*;

public class Test {
    public static void main(String[] args)
    {
        Connection connection = null;
        try
        {
            // create a database connection
            connection = DriverManager.getConnection("jdbc:sqlite:/C:/rexon_metals.db");
            Statement statement = connection.createStatement();

            ResultSet rs = statement.executeQuery("SELECT REGION FROM CUSTOMER WHERE REGION = 'Southwest'");
            while(rs.next())
            {
                String region = rs.getString("REGION");
                System.out.println(region + ": " + System.identityHashCode(region));
            }
        }
        catch(SQLException e)
        {
            // if the error message is "out of memory",
            // it probably means no database file is found
            System.err.println(e.getMessage());
        }
        finally
        {
            try
            {
                if(connection != null)
                    connection.close();
            }
            catch(SQLException e)
            {
                // connection close failed.
                System.err.println(e);
            }
        }
    }
}

CONCLUSION:

Southwest: 405662939
Southwest: 653305407
Southwest: 1130478920
Southwest: 1404928347

But if I explicitly call the method String.intern(), all identity hash codes are the same.

String region = rs.getString("REGION").intern();

CONCLUSION:

Southwest: 405662939
Southwest: 405662939
Southwest: 405662939
Southwest: 405662939

JDBC intern() ? , String? ?

P.S. - String, . , , intern()?

+4
1

JDBC String, .

, , , , - , JDBC, , , .

, String , intern(). , Strings , , , - , , .

, , , , . , , , , , id.

+5

Source: https://habr.com/ru/post/1668044/


All Articles