PositionManager.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright (c) 2003, 2004 Per M.A. Bothner.
  2. // This is free software; for terms and warranty disclaimer see ./COPYING.
  3. package gnu.lists;
  4. public class PositionManager
  5. {
  6. static final PositionManager manager = new PositionManager();
  7. static public SeqPosition getPositionObject (int ipos)
  8. {
  9. PositionManager m = manager;
  10. synchronized (m)
  11. {
  12. return m.positions[ipos];
  13. }
  14. }
  15. SeqPosition[] positions = new SeqPosition[50];
  16. int[] ivals = new int[50];
  17. int freeListHead = -1;
  18. private void addToFreeList(int[] ivals, int first, int end)
  19. {
  20. int head = freeListHead;
  21. for (int i = first; i < end; i++)
  22. {
  23. ivals[i] = head;
  24. head = i;
  25. }
  26. freeListHead = head;
  27. }
  28. private int getFreeSlot ()
  29. {
  30. int head = freeListHead;
  31. if (head < 0)
  32. {
  33. int old_size = positions.length;
  34. SeqPosition[] npositions = new SeqPosition[2 * old_size];
  35. int[] nvals = new int[2 * old_size];
  36. System.arraycopy(positions, 0, npositions, 0, old_size);
  37. System.arraycopy(ivals, 0, nvals, 0, old_size);
  38. positions = npositions;
  39. ivals = nvals;
  40. addToFreeList(nvals, old_size, 2 * old_size);
  41. head = freeListHead;
  42. }
  43. freeListHead = ivals[head];
  44. return head;
  45. }
  46. public PositionManager ()
  47. {
  48. // We don't use positions[0], because ipos==0 is reserved for
  49. // createPosition(0, false).
  50. addToFreeList(ivals, 1, ivals.length);
  51. }
  52. public synchronized int register(SeqPosition pos)
  53. {
  54. int i = getFreeSlot();
  55. positions[i] = pos;
  56. ivals[i] = -1;
  57. return i;
  58. }
  59. public synchronized void release(int ipos)
  60. {
  61. SeqPosition pos = positions[ipos];
  62. if (pos instanceof ExtPosition)
  63. ((ExtPosition) pos).position = -1;
  64. positions[ipos] = null;
  65. ivals[ipos] = freeListHead;
  66. freeListHead = ipos;
  67. pos.release();
  68. }
  69. }