CustomizedConcurrentQueue.java 888 B

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