Guest User

Untitled

a guest
Jun 22nd, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. package net.cakenet.rsps.component;
  2.  
  3. import net.cakenet.rsps.Stream;
  4.  
  5. /**
  6. * The @code ComponentManager} is used to create resources on the fly for reusable components and then hold them when
  7. * they're finished with so that they can be reused later
  8. *
  9. * @author James Lawrence
  10. * @version 1
  11. */
  12. public final class ComponentManager {
  13. private static ComponentList<Stream> streamComponents;
  14.  
  15. static {
  16. streamComponents = new ComponentList<Stream>();
  17. }
  18.  
  19. private ComponentManager() {}
  20.  
  21. /**
  22. * Retrieves a stream object with the specified length from the component manager, or creates one if needed.
  23. * After the stream has been acquired by the calling code, it MUST be released by called releaseStream at the end of
  24. * usage, otherwise memory is being wasted and the object wont be reused!
  25. * @param length the required buffer length of the stream
  26. * @return the acquired or created stream object
  27. */
  28. public static Stream acquireStream(int length) {
  29. Stream head = streamComponents.getFirst();
  30. while(head != null) {
  31. if(head.capacity == length) {
  32. // Remove it from the list (acquiring block should re-add it when it's finished)
  33. head.remove();
  34. return head;
  35. } else if(head.capacity > length)
  36. return new Stream(new byte[length]);
  37. head = streamComponents.getNext();
  38. }
  39. // There wasn't one, create one
  40. return new Stream(new byte[length]);
  41. }
  42.  
  43. /**
  44. * Releases the lock from a stream component
  45. * @param s the stream component to retrieve and unlock
  46. */
  47. public static void releaseStream(Stream s) {
  48. long highId = 0;
  49. final int searchCapacity = s.capacity;
  50. Stream head = streamComponents.getFirst();
  51. while(head != null) {
  52. if(head.capacity > searchCapacity) {
  53. // Insert it before this component and return
  54. streamComponents.addNext(s);
  55. return;
  56. }
  57. head = streamComponents.getNext();
  58. }
  59. // Add tail...
  60. streamComponents.addTail(s);
  61. }
  62. }
Add Comment
Please, Sign In to add comment