/hazelcast/src/main/java/com/hazelcast/util/SimpleBoundedQueue.java

https://bitbucket.org/gabral6_gmailcom/hazelcast · Java · 110 lines · 77 code · 13 blank · 20 comment · 13 complexity · d8d84c0782bd6bbc724db65a5fb21c5c MD5 · raw file

  1. /*
  2. * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.hazelcast.util;
  17. import java.util.AbstractQueue;
  18. import java.util.Iterator;
  19. /**
  20. * Not Thread-Safe
  21. *
  22. * @param <E>
  23. */
  24. public final class SimpleBoundedQueue<E> extends AbstractQueue<E> {
  25. final int maxSize;
  26. final E[] objects;
  27. int add = 0;
  28. int remove = 0;
  29. int size = 0;
  30. public SimpleBoundedQueue(int maxSize) {
  31. this.maxSize = maxSize;
  32. objects = (E[]) new Object[maxSize];
  33. }
  34. @Override
  35. public boolean add(E obj) {
  36. if (size == maxSize) {
  37. return false;
  38. }
  39. objects[add] = obj;
  40. add++;
  41. size++;
  42. if (add == maxSize) {
  43. add = 0;
  44. }
  45. return true;
  46. }
  47. public E pop() {
  48. if (size == 0)
  49. return null;
  50. int last = add - 1;
  51. E value = objects[last];
  52. objects[last] = null;
  53. size--;
  54. add--;
  55. return value;
  56. }
  57. @Override
  58. public int size() {
  59. return size;
  60. }
  61. public int remainingCapacity() {
  62. return maxSize - size;
  63. }
  64. public boolean offer(E o) {
  65. return add(o);
  66. }
  67. public E peek() {
  68. if (size == 0)
  69. return null;
  70. return objects[remove];
  71. }
  72. public E poll() {
  73. if (size == 0)
  74. return null;
  75. E value = objects[remove];
  76. objects[remove] = null;
  77. remove++;
  78. size--;
  79. if (remove == maxSize) {
  80. remove = 0;
  81. }
  82. return value;
  83. }
  84. @Override
  85. public void clear() {
  86. for (int i = 0; i < maxSize; i++) {
  87. objects[0] = null;
  88. }
  89. add = 0;
  90. remove = 0;
  91. size = 0;
  92. }
  93. @Override
  94. public Iterator<E> iterator() {
  95. throw new UnsupportedOperationException();
  96. }
  97. }