0

Java String is immutable so

when you create a string, a block of memory is assigned for it in the heap, and when you change its value, a new block of memory is created for that string, and the old one becomes eligible for garbage collection, for example

String str = func1_return_big_string_1()"; //not literal
String str= func2_return_big_string_2()"; //not literal

But as garbage collection takes time to kick in so we are practically have memory in heap containing both big string 1 & 2. They can be a issue for me if this happens a lot.

Is there a way to make big string 2 to use the same location in memory of string 1 so we don't need have extra space when we assign big string 2 to str.

Edit: Thanks for all the input and in the end I realized I shouldn't expecting java code to behave like c++ code(i.e, different memory footprint). I have wrote a c++ 11 demo which works as expected, biggest memory footprint is around 20M (biggest file I was trying to load) with rvalue reference and move assignment operator all kick in as expected. Below demo done in VS2012 with c++ 11.

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <thread>
using namespace std;

string readFile(const string &fileName)
{
    ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);

    ifstream::pos_type fileSize = ifs.tellg();
    ifs.seekg(0, ios::beg);

    vector<char> bytes(fileSize);
    ifs.read(&bytes[0], fileSize);

    return string(&bytes[0], fileSize);
}

class test{
public:
    string m_content;
};

int _tmain(int argc, _TCHAR* argv[])
{
    string base("c:\\data");
    string ext(".bin");
    string filename;
    test t;
    //std::this_thread::sleep_for(std::chrono::milliseconds(5000));
    cout << "about to start" << endl;
    for(int i=0; i<=50; ++i) {
        cout << i << endl;
        filename = base + std::to_string(i) + ext;
        //rvalue reference & move assignment operator here
        //so no unnecessary copy at all
        t.m_content = readFile(filename);
        cout << "szie of content" << t.m_content.length() << endl;
    }
    cout << "end" << endl;
    system("pause");
    return 0;
}
12
  • These aren't string literals we're talking about, right? Presumably the big strings are returned from some method, correct?
    – arshajii
    Oct 20, 2013 at 16:18
  • 1
    Use a Char array instead? Looking through the API, I only see String.replace() as a likely candidate, but that requires you to use Regex on it, and I dont know how the memory allocation works for that Oct 20, 2013 at 16:19
  • @arshajii: yes thats right
    – RoundPi
    Oct 20, 2013 at 16:21
  • 3
    Secondly, have you done any tests to determine that there is really a memory issue here? The GC should be pretty efficient when it comes to this.
    – arshajii
    Oct 20, 2013 at 16:23
  • No but I can foreseeen this could happen, at least I don't want to reply on GC if I don't have to.
    – RoundPi
    Oct 20, 2013 at 16:26

5 Answers 5

2

Use StringBuffer, StringBuffer.append()

2
  • 1
    I think he wants to completely reassign str to a new string, not somehow mutate a preexisting one.
    – arshajii
    Oct 20, 2013 at 16:24
  • Is it possible in Java? Java's Strings are immutable. The only option to make them mutable is to use (like @Praveen suggested) StringBuffer or StringBuilder class. Oct 20, 2013 at 16:28
2

I see several options:

  1. Use char[].
  2. Copy StringBuilder into your version MyStringBuilder with a public reusable buffer. The major disadvantage is that it lacks regexes. That's what I did when I needed to boost performance.
  3. Hack for JDK <=6: there is a protected constructor to reuse strings/wrap char buffers. It's not there anymore for JDK 7+. One needs to be really cautious with this, and it's not a problem once you have C/C++ background.
  4. Copy String into the MutableString with a public reusable buffer. I don't think there would a problem adding your custom regex matcher as there are a plenty of them available.
2
  • I don't need to worry about regexes for this particular case, so could you give a example of your 2> solution?
    – RoundPi
    Oct 20, 2013 at 23:34
  • Here is a sample. reset() method was added and a few others to reuse the StringBuilder. Oct 21, 2013 at 9:16
1

In order to avoid having both the old and new String at the same time in memory, you can explicitly allow the GC to clean it up by assigning null to the variable:

String str;
str = func1_return_big_string_1();
str = null; // Now, GC can clean, when it needs extra memory for the String.
str = func2_return_big_string_2();

UPDATE: To support my claim, I wrote a test case that proves I'm right: http://ideone.com/BwGfSN. The code demonstrates the difference between (using the Finalizer):

GCTest test;
// Without the null assignment
test = create(0);
test = create(1);
test = null;
System.gc();

try {Thread.sleep(10);} catch (Exception e){}
System.out.println();

// With the null assignment
test = create(2);
test = null;
test = create(3);
test = null;
System.gc();
14
  • Yes, you can. By calling System.gc(). But that is not what I'm showing here. The idea is to release the previous String object, in order to allow the GC to kick in while creating the string within func2. Oct 21, 2013 at 5:36
  • Funny to see how everybody is downvoting, while this is really the technical answer to his problem. Oct 21, 2013 at 11:34
  • 1
    @AndreyChaschev: No, that is not true. While in the func2_return_big_string_2() method, the reference to the other big string (stored in str) still exists. Only when the method returns, the value of str is overwritten. So, while creating the next big string, the GC can't free the previous one. Therefor, assigning it to null allows the GC to get rid of it, when func2_return_big_string_2() is allocating the next one. Oct 21, 2013 at 17:55
  • 2
    @MartijnCourteaux: Could we agree that JIT is the optimizing compiler? Could we also agree that JVM can run without it? If not, please take a look here. The first few iterations are always interpreted, agreed?
    – maaartinus
    Jan 30, 2014 at 3:03
  • 1
    To settle this old case, @maaartinus is right. This can be demonstrated by raising the sleep times in this program and then running it with -Xcomp. Eliminating variables with are not read, is one of the the JIT’s simplest tricks. But a method running a single time, like this main method usually doesn’t get optimized and even if, switching an already running method to a compiled version has significant restrictions. See also Can java finalize an object when it is still in scope?
    – Holger
    Nov 23, 2023 at 15:50
1

It shouldn't really matter for non-interned Strings. If you start running out of memory, the garbage collector will remove any objects that are no longer referenced.

Interned Strings are much harder to collect, see Garbage collection of String literals for details

EDIT A non-interned String is just like a normal object. Once there are no more references to it, it will get garbage collected.

if str is the only reference left pointing to the original String and str is changed to point to something else, then the original String is eligible for garbage collection. So you no longer have to worry about running out of memory because the JVM will collect it if memory is required.

3
  • @Gob00st then my second sentence is my answer
    – dkatzel
    Oct 20, 2013 at 16:27
  • I am not sure I get your answer, do you care to explain more? also edited my question.
    – RoundPi
    Oct 20, 2013 at 16:31
  • @Yes without reference GC will collect eventually I was hoping it can does the job quickly so the memory doesn't have to spike up.
    – RoundPi
    Oct 22, 2013 at 15:45
1

I have just found a MutableString implementation. It is available in Maven Central. Here is an extract from their JavaDoc page:

  • Mutable strings occupy little space— their only attributes are a backing character array and an integer;
  • their methods try to be as efficient as possible: for instance, if some limitation on a parameter is implied by limitation on array access, we do not check it explicitly, and Bloom filters are used to speed up multi-character substitutions;
  • they let you access directly the backing array (at your own risk);
  • they implement CharSequence, so, for instance, you can match or split a mutable string against a regular expression using the standard Java API;
  • they implement Appendable, so they can be used with Formatter and similar classes;

UPDATE

You can utilize Appendable interface of this MutableString to read a file with almost zero-memory overhead (8KB, which is the default buffer size in Java). With Guava's CharStreams.copy it looks like this:

MutableString str = new MutableString((int) file.length());
CharStreams.copy(Files.newReaderSupplier(file, Charset.defaultCharset()), str);
System.out.println(str);

Full working example.

6
  • Great! Accepting an answer motivates our future contributions! :-) Oct 22, 2013 at 16:26
  • Though it's not saving much because when the mutable string does the append, it's copying the char array loaded from file into it's own array. I was hoping it can do move semantic with rvalue reference in c++ 11: meaning pointing it's array point to the temp object's array(loaded from file), but its not doing the smart thing... Anything upvote for you. Cheers
    – RoundPi
    Oct 22, 2013 at 16:57
  • I've updated an answer with an example of buffered reading into this MutableString. HTH Oct 22, 2013 at 17:18
  • The code won't compile: The generic method copy(InputSupplier<R>, OutputSupplier<W>) of type CharStreams is not applicable for the arguments (InputSupplier<FileInputStream>, MutableString). The inferred type FileInputStream is not a valid substitute for the bounded parameter <R extends Readable & Closeable>
    – RoundPi
    Oct 22, 2013 at 17:47
  • 1
    For a lot of use cases, the built-in CharBuffer will be sufficient. It can wrap a char[] array and implements Appendable, CharSequence, Readable, and in recent versions even Comparable<CharBuffer>. But mutable data structures are not always the most efficient solution. In the best case, Files.readString(path) works without any intermediate buffers.
    – Holger
    Nov 23, 2023 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.