javareaderstringreader

Reusable Java StringReader


Is there any way of implementing a StringReader class that allows reusing the same StringReader (or similar functionality) object with more than one strings, without changing any of its functionality (methods)?

For example, such a Java class (say, ReusableStringReader) would be a subclass of java.io.StringReader, with an extra method like

public void reset(String str);

which would assign the new string value to the internal StringReader parameter, so that all subsequent calls to the read() methods of the StringReader use the new value. Such a "reusability" is very convenient when one wants to restrict the number of objects used by an application (e.g., one that handles very large number of strings per second via a Reader object).

General ways to achieve this would be:

  1. Inheritance. All the internal state of StringReader is stored in private instance variables, so this is not an option.
  2. Reflection. Reset the internal state of the StringReader object via reflection. There are 4 instance variables to set, which means 4 reflection calls per "reset(String)" call (not too efficient).
  3. Composition. One could use a reusable StringInputStream and from that create a Reader object via InputStreamReader, then use that Reader internally in a subclass of StringReader, to implement the full API of the StringReader class. This is quite a hack, though.

Any ideas for a better solution?


Solution

  • I think you are most likely prematurely optimizing a non-problem here, unless you have actually measured to see that StringReader instances cause severe GC pressure. It is much more likely that allocations that occur due to reading of content are more meaningful.

    So I would not worry at all about reusability: use-once instances are much safer and simpler. In general it is relatively rare to actually benefit from reuse of light-weight objects such as readers.

    If you still want to pursue this, however, just write your own Reader with reset(), and do not worry about JDK variant. You may peek at implementation, but it is dead simple. There's little benefit from trying to sub-class, delegate or compose: especially if you are really concerned amount minimal allocations.