简体   繁体   中英

Java Char Buffer that automatically grows and can be re-used

Hello Java Developers:

I'm looking for a built in class to store a sequence of characters. It needs to meet the following criteria:

  1. It can store char values (not just byte values)
  2. It has an append method that causes the underlying data structure to automatically grow in size should it exceed the pre-allocated size.
  3. Has a method to clear the contents (ie re-use the memory).
  4. Can read the entry at a given index.

I've found several options that meet some of these requirements but not all of them. For instance:

  1. CharBuffer does not satisfy 2.
  2. StringBuffer does not satisfy 3.
  3. ByteArrayOutputStream does not satisfy 1.
  4. CharArrayWriter does not satisfy 4.

Am I misinterpreting the documentation for one of these classes, or does someone out there know of a data structure that meets all 4 criteria?

Edit: By criteria 3, I don't mean free memory to GC.

I'm in the situation where I need to repeatedly allocate and de-allocate several of these buffers. In my use case, these buffers end up being fairly large (~ 100 KB) and I would have several threads using such buffers.

I'm aware that I could just create a buffer, use it and then have it GC-ed when I'm done. However, I've found that the JVM garbage collector runs quite slowly when you are constantly allocating and de-allocating a large percent of the JVM (and physical machine's) memory. I've found speed improvements when I start micromanaging the memory (like one can do in C++) by allocating a buffer once and then re-using it (thus triggering garbage collection less frequently).

StringBuilder/StringBuffer should satisfy 3 fine since delete(...) should do what you need. Or why not simply create a new instance and let the old one be GC'd?

StringBuffer可以删除其内容

buffer.delete(0, buffer.length());

Solution that I've found: StringBuilder has .setLength(0) which I can use to get the buffer to start re-writing contents.

(A dedicated .reset() method would have been nice.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM