Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:

Dynamic memory; classes Vector and StringBuffer

How to dynamically allocate memory, solve Vector memory errors, and add stings

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

QI 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?

ATo 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:

About the author

Random Walk Computing is the largest Java/CORBA consulting boutique in New York, focusing on solutions for the financial enterprise. Known for their leading-edge Java expertise, Random Walk consultants publish and speak about Java in some of the most respected forums in the world.
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());


  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comment
Login
Forgot your account info?
Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources