1

I have a bluetooth connection to a device that sends data as a byte array. The byte array is then changed to a string with new String(byte[], offset, bytecount). The problem is that data is received hundreds and hundreds of times and the garbage collection does not seem to be doing it's job because after about 1000 loops, I get an out of memory byte allocation error. The app starts to lag more and more as the loops increase as well.

Is there a way to free the memory of the new string object right after I use it or better yet, is there a way to change the byte array to a string or even a float without creating a new object?

Worse case, is there a way to give the app more memory so the error happens much later?

1 Answers1

0

If you read your data into a char[], and reuse that array as you read more data, you will have a very small memory footprint.

Also, check out this page: http://www.javamex.com/tutorials/memory/string_memory_usage.shtml

TotoroTotoro
  • 17,524
  • 4
  • 45
  • 76
  • So use char[] instead of byte[] but what about the offset and bytecount? Does it not matter for char[] to String? – user1233402 Feb 26 '12 at 05:51
  • I don't think it matters if you use byte[] or char[]. I was actually thinking of InputStreamReader, which can output into a char[]: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/InputStreamReader.html#read(char[],%20int,%20int). You specify the offset and byte count there. Is that what you're asking? – TotoroTotoro Feb 26 '12 at 06:00
  • haha I honestly don't know how to ask my question. I'm getting hundreds of byte[] which I need to change to Strings in order to get useful information and I want to do it without creating a new object. Use InputStreamReader with byte[] as input and set offset and bytecount with read(char[], offset, bytecount) to get my char[]? – user1233402 Feb 26 '12 at 06:18
  • Ok, I see. So what you wanna do is to parse your byte[] array, and extract useful info from it, right? Right now you're creating strings from that array. The strings are very easy to parse, but they take up lots of memory. So what you wanna do is to parse the byte array directly, thereby saving the precious memory. How to do it is another question. It's not hard, just more code :) This may get you started: http://stackoverflow.com/questions/5106531/parsing-byte-array-in-java. – TotoroTotoro Feb 26 '12 at 06:23
  • Thanks! that sounds about right. I was hoping there was an easy way to convert the byte array to a String without creating a new string object. Guess it's going to be a long night – user1233402 Feb 26 '12 at 06:43