Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package net.cakenet.rsps.component;
- import net.cakenet.rsps.Stream;
- /**
- * The @code ComponentManager} is used to create resources on the fly for reusable components and then hold them when
- * they're finished with so that they can be reused later
- *
- * @author James Lawrence
- * @version 1
- */
- public final class ComponentManager {
- private static ComponentList<Stream> streamComponents;
- static {
- streamComponents = new ComponentList<Stream>();
- }
- private ComponentManager() {}
- /**
- * Retrieves a stream object with the specified length from the component manager, or creates one if needed.
- * After the stream has been acquired by the calling code, it MUST be released by called releaseStream at the end of
- * usage, otherwise memory is being wasted and the object wont be reused!
- * @param length the required buffer length of the stream
- * @return the acquired or created stream object
- */
- public static Stream acquireStream(int length) {
- Stream head = streamComponents.getFirst();
- while(head != null) {
- if(head.capacity == length) {
- // Remove it from the list (acquiring block should re-add it when it's finished)
- head.remove();
- return head;
- } else if(head.capacity > length)
- return new Stream(new byte[length]);
- head = streamComponents.getNext();
- }
- // There wasn't one, create one
- return new Stream(new byte[length]);
- }
- /**
- * Releases the lock from a stream component
- * @param s the stream component to retrieve and unlock
- */
- public static void releaseStream(Stream s) {
- long highId = 0;
- final int searchCapacity = s.capacity;
- Stream head = streamComponents.getFirst();
- while(head != null) {
- if(head.capacity > searchCapacity) {
- // Insert it before this component and return
- streamComponents.addNext(s);
- return;
- }
- head = streamComponents.getNext();
- }
- // Add tail...
- streamComponents.addTail(s);
- }
- }
Add Comment
Please, Sign In to add comment