KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > gnu > lists > PositionManager


1 // Copyright (c) 2003, 2004 Per M.A. Bothner.
2
// This is free software; for terms and warranty disclaimer see ./COPYING.
3

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