Wizard API updated!
Tim Boudreau has released a new version of the Swing Wizard library (version 0.997) that fixes the WizardException bug reported in JavaWorld's recent Open Source Java Project profile. The article's examples have been reworked to test out the new, improved WizardException. Thanks, Tim, for this helpful fix!
Open Source Java Projects: The Wizard API

Newsletter sign-up

Sign up for our technology specific newsletters.

Enterprise Java
View all newsletters

Email Address:

Dynamic memory; classes Vector and StringBuffer

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

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:

Author Bio

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());


Resources