Search code examples
javamemory-managementout-of-memorystring-interningstring-pool

Would writing millions of strings through a Writer be a memory and performance concern for the java string pool?


So say I have this code that streams back string back to a client with millions of rows of data. Would all the strings on each write be interned and thus give a hit on the java memory? If so, why in my case would it be or not be interned?

I can't really tell if I should use a stringbuilder here to append all the things I am gonna write and then write them at the end or just leave it as is

The query would return millions of rows  

try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()))) {

            writer.write("[");
            jdbcTemplate.query(sql, new Object[]{name,  age},

                    rs -> {

                        try {

                            writer.write("{\"id1\":" + rs.getInt("id1") + ",");

                            writer.write("\"id2\":" + rs.getInt("id2") + "}");

                        } catch (IOException e) {

                            log.log(Level.ERROR, e);

                        }

                    });

            writer.write("]");

        } catch (IOException e) {

            throw e;

        }

Solution

  • No Strings will ever be interned at run-time unless you call .intern() on them. You're not in any danger of blowing up the intern pool.

    It might help speed things up if you assembled your strings with StringBuilder, but it won't make any difference in overall memory consumption. Every string you are making is gone and forgotten once your BufferedWriter and OutputStreamWriter have finished writing it to its destination.