tmn*_*tmn 4 java string jvm jdbc
我的同事和我的应用程序存在一些内存问题,我们发现的一个发现是来自数据库的字符串值(高度重复)实际上没有被实现.因此,重复值保存在内存中,这可能是一个巨大的问题.
例如,这是一个简单的JDBC示例,它从SQLite数据库中查询相同的字符串.我打印每个的身份哈希码,它显示每个是一个单独的实例.
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
Southwest: 405662939
Southwest: 653305407
Southwest: 1130478920
Southwest: 1404928347
Run Code Online (Sandbox Code Playgroud)
但是,如果我显式调用该String.intern()方法,则所有标识哈希码都是相同的.
String region = rs.getString("REGION").intern();
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
Southwest: 405662939
Southwest: 405662939
Southwest: 405662939
Southwest: 405662939
Run Code Online (Sandbox Code Playgroud)
为什么JDBC不要求intern()我?如果有许多重复String值,开发人员是否应该这样做?这是经常使用的,并在整个应用程序的会话期间持续存在?
PS - 有数百万个String值可以合并到几百个.这是否需要手动intern()调用?
JDBC驱动程序不会从数据库中检索实时字符串数据.
您需要考虑实习是相对昂贵的,并且驱动程序无法轻易预测哪些数据是高度重复的,哪些不是 - 特别是因为JDBC结果集很可能在客户端代码遍历时从数据库中逐位流式传输.
如果内存是您的应用程序的主要瓶颈,并且您的String数据是高度重复的,您可以手动实习()它.请注意,这仍然不会阻止驱动程序创建字符串,唯一改变的是,一旦它们超出范围,副本就会变成垃圾收集.
但是,如果你在你的数据库有这样的重复的字符串,我肯定如果数据库设计不当看看先.如果事实证明字符串实际上表示固定集合,则考虑将它们转换为代码表,其可以由例如id表示.
| 归档时间: |
|
| 查看次数: |
166 次 |
| 最近记录: |