Re:Implementation of a RingBuffer in Java with optional FIFO...
by stickfigure on Wednesday February 05, 2025 @02:51PM
(#42954128)
Why does the constructor need the Class<?> parameter?
[ Parent
| on HN ]
Re:Implementation of a RingBuffer in Java with optional FIFO...
by jcrites on Wednesday February 05, 2025 @03:08PM
(#42954391)
Looking at the source, I don't think there's an actual need for the constructor to take a `Class<T>` type. It's used internally to initialize an array [1]:
this.entries = (T[]) Array.newInstance(type, capacity);
However, I think this alternative would work equally well, and would not require a `Class<T>` parameter: this.entries = (T[]) new Object[capacity];
There are some other choices in the library that I don't understand, such as the choice to have a static constructor with this signature: public static RingBuffer<Object> create(final int capacity) {
return create(capacity, false);
}
This returns the type `RingBuffer<Object>`, which isn't as useful as it could be; with appropriate idiomatic use of generics it could return a `RingBuffer<T>`: public static <T> RingBuffer<T> create(final int capacity, final boolean orderedReads) {
return new RingBuffer<>(capacity, orderedReads);
}
It's possible that this code was written by someone who is still learning idiomatic Java style, or effective use of generics.I'm also curious about the choice to have `get()` return `null`. I think I'd rather have seen this modeled with `Optional`. My preferred style when writing Java code is to employ non-nullable references wherever possible (though the return from `get()` is marked `@Nullable` at least).
[1] https://github.com/evolvedbinary/j8cu/blob/94d64cfc0ec49a340...
Re:Implementation of a RingBuffer in Java with optional FIFO...
by o11c on Wednesday February 05, 2025 @02:59PM
(#42954253)
That's about the least-bad thing about the code here - it's a workaround for the fact that Java lacks runtime support for generics.
Other than its indirect use in `copy` (which in Java normally takes the parameter itself), it's probably not actually necessary here since you could just use `Object[]`? But I don't spend enough time in Java (thankfully) so I'm not sure if there are intricacies involving the runtime overhead of casting.
Re:Implementation of a RingBuffer in Java with optional FIFO...
by IncreasePosts on Wednesday February 05, 2025 @03:11PM
(#42954443)
Line 115: this.entries = (T[]) Array.newInstance(type, capacity)
You can't just say new T[capacity] in java.