Dynamic memory; classes Vector and StringBuffer
How to dynamically allocate memory, solve Vector memory errors, and add stings
Q: I want to allocate memory dynamically for any type. In addition, when I use the Vector class it sometimes causes an OutOfMemoryError . How I can handle this situation?
A separate problem I have occurs when I want to make a large string by continuously adding small strings. Using the +
operator to overload the String
class takes too much time. How I can do this in a faster way?
A: To answer your question about dynamic memory, when you create an object using new
, it is like malloc()
in C/C++. That is, it allocates memory when you create the object; it is dynamic.
To solve your problem with the Vector
class and the OutOfMemoryError
, keep a thread checking for the total memory and free memory. If you run out of memory, release references to unwanted objects and call gc. fee
with the following code:
Runtime rt = Runtime.getRuntime();
long total = rt.freeMemory();
long free = rt.freeMemory();
if(total-free < 5000000) { //if it is less than 1MB
//release refs to some objects here
//the systems that create cache will release
//LRU objects here
rt.gc();
}
To answer your question about strings, use the StringBuffer
class. String
is an immutable object, which means you can’t change it. Any change would have to create a new Object
. In contrast, StringBuffer
is much faster and mutable — you can append to it without creating a new object. Here’s how you do it:
String initialString = "initial ";
StringBuffer sb = new StringBuffer(initialString);
String newString = "some thing new ";
//use append as many times as you want
sb.append(newString);
//and when you want to get String
System.err.println(sb.toString());