CustomizedConcurrentQueue2.java 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package com.oblivm.backend.network;
  2. public class CustomizedConcurrentQueue2 {
  3. int capacity;
  4. int head = 0;
  5. int tail = 0;
  6. byte[] data;
  7. boolean finished = false;
  8. public CustomizedConcurrentQueue2(int capacity) {
  9. this.capacity = capacity;
  10. data = new byte[capacity];
  11. }
  12. public void destory() {
  13. finished = true;
  14. }
  15. public int insert(byte[] in) {
  16. int remains = capacity - head;
  17. if (remains >= in.length) {
  18. System.arraycopy(in, 0, data, head, in.length);
  19. head += in.length;
  20. } else {
  21. System.arraycopy(in, 0, data, head, remains);
  22. System.arraycopy(in, remains, data, 0, in.length - remains);
  23. head = in.length - remains;
  24. }
  25. return 0;
  26. }
  27. synchronized public int pop(byte[] d) {
  28. int h = head;
  29. int size = (h - tail + capacity) % capacity;
  30. // if(h != 0)
  31. // System.out.println(h+" "+size+" "+tail+" "+size);
  32. if (finished && size == 0)
  33. return -1;
  34. if (size == 0)
  35. return 0;
  36. // System.out.println(size);
  37. if (h > tail) {
  38. System.arraycopy(data, tail, d, 0, h - tail);
  39. } else {
  40. System.arraycopy(data, tail, d, 0, capacity - tail);
  41. System.arraycopy(data, 0, d, capacity - tail, h);
  42. }
  43. // System.out.println("!!");
  44. tail = h;
  45. return size;
  46. }
  47. }