On Tue, 8 Oct 2024 12:30:03 GMT, Chen Liang <[email protected]> wrote:
>> As the anonymous class MUST NOT be used with multiple threads, I always have
>> seen the `CharSequence` as *fixed/static* text in the moment the `Reader` is
>> getting used. But indeed, technically one could interleave `Reader::read()`
>> invocations by `CharSequence.append()` (or even worse,
>> `CharSequence.delete()`) invocations. The question is: Would that make *any*
>> sense in the end? I mean, what happens if one has `read()` text that in the
>> next step gets `delete()`'d? I cannot image *any* scenario where such a
>> program would result in *useful* outcome.
>>
>> <fun>The fact that nobody so far (before you) brought up this question
>> seems to proof that nobody (besides you) would write such a program. 😄
>> </fun>
>>
>> So I would plea for clearly saying in the JavaDocs that `cs` MUST NOT be
>> modified before `close()` is called. Every other solution implies strange
>> side effects and slower and error-prone implementation of both, anoynous
>> reader *and* test.
>>
>> @AlanBateman WDYT?
>
> I would treat this specific scenario as one of the "no concurrent usage"
> examples. Note that by this principle, mutable objects like `StringBuilder`
> should not override object comparison methods as these states can change, but
> they do :(
> The question is: Would that make any sense in the end?
Consider the example of `StringBuffer`, which is a `CharSequence`. Wouldn't
something like the following be a logical use of `Reader.of(CharSequence)`,
where you create a `Reader` for the underlying sequence (which is not yet
populated) and then keep reading through the `Reader` until the underlying
sequence's data is finished?
final StringBuffer sb = new StringBuffer();
try (final Reader reader = Reader.of(sb)) {
final ContentGenerator cg = new ContentGenerator(sb);
Thread.ofPlatform().start(cg);
int numRead = 0;
while (numRead != -1) {
final char[] content = new char[1024];
numRead = reader.read(content); // wait for content
}
}
private class ContentGenerator {
final StringBuffer sb;
ContentGenerator(StringBuffer sb) {
this.sb = sb;
}
@Override
run() {
while (true) {
String foo = getSomeContent(); // maybe blocking
sb.append(foo);
}
}
}
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/21371#discussion_r1791789988