black
black

Reputation: 357

Java Memory Leak in JDBC ResultSet/Statement

I have a self-written mini library which is supposed to be working with MySQL db using reflection and annotations. For some reason my application, which uses its code has a memory leak problem. When I profiled it it detected a huge memory consumption by char arrays. Could anyone explain me whats wrong? (One of the function's code which causes memory leaks)

public List select(Class clazz, String condition, Object... values) throws Exception{
    Table tbl = (Table) clazz.getAnnotation(Table.class);
    if(tbl==null) throw new Exception("Specified class doesnt contain table information");

    StringBuilder strb = new StringBuilder().append("SELECT * FROM `");
    strb.append(prefix).append(tbl.name());
    strb.append("` WHERE ");
    strb.append(condition);

    PreparedStatement stmt = con.prepareStatement(strb.toString());
    for (int i = 0; i < values.length; i++) {
        stmt.setObject(i + 1, values[i]);
    }

    ResultSet rs = stmt.executeQuery();
    ArrayList result = new ArrayList<>();
    while(rs.next()){
        Object o = clazz.newInstance();
        for(Field f : clazz.getFields()){
            Table.Column col = f.getAnnotation(Table.Column.class);
            if(col!=null){
                if(!f.isAccessible())
                    f.setAccessible(true);
                f.set(o, rs.getObject(f.getName()));
            }
        }
        result.add(o);
    }
    return result;
}

Thank you in advance. PS I am not using List or elements in the List returned by this func for test purposes

Upvotes: 0

Views: 1527

Answers (1)

Leo
Leo

Reputation: 6570

You have to close the result set and statement.

Upvotes: 2

Related Questions