]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/BinaryQueryHash.java
Fixed multiple issues causing dangling references to discarded queries
[simantics/platform.git] / bundles / org.simantics.db.impl / src / org / simantics / db / impl / query / BinaryQueryHash.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.db.impl.query;
13
14 import gnu.trove.impl.hash.THash;
15
16 import java.lang.reflect.Array;
17
18 import org.simantics.db.exception.DatabaseException;
19 import org.simantics.db.impl.graph.ReadGraphImpl;
20
21
22 /**
23  * An open addressed hashing implementation for Object types.
24  *
25  * Created: Sun Nov  4 08:56:06 2001
26  *
27  * @author Eric D. Friedman
28  * @version $Id: BinaryQueryHash.java,v 1.2 2008/03/14 11:38:53 tuoksk Exp $
29  */
30 abstract public class BinaryQueryHash<Procedure> extends THash {
31     static final long serialVersionUID = -3461112548087185871L;
32
33     /** the set of Objects */
34     protected transient BinaryQuery<Procedure>[] _set;
35
36     protected final BinaryQuery<Procedure> REMOVED = new BinaryQuery<Procedure>(-1, -1) {
37
38         @Override
39         public void removeEntry(QueryProcessor provider) {
40             throw new Error("Not possible!");
41         }
42
43         @Override
44         public int type() {
45             throw new Error("Not possible!");
46         }
47
48                 @Override
49                 Object performFromCache(ReadGraphImpl graph, Procedure procedure) throws DatabaseException {
50             throw new Error("Not possible!");
51                 }
52
53                 @Override
54                 public void recompute(ReadGraphImpl graph) throws DatabaseException {
55             throw new Error("Not possible!");
56                 }
57         
58     };
59
60     /**
61      * Creates a new <code>TObjectHash</code> instance with the
62      * default capacity and load factor.
63      */
64     public BinaryQueryHash() {
65         super(DEFAULT_CAPACITY, 0.75f);
66     }
67
68     public int capacity() {
69         return _set.length;
70     }
71
72     protected void removeAt(int index) {
73         _set[index] = REMOVED;
74         super.removeAt(index);
75     }
76
77     /**
78      * initializes the Object set of this hash table.
79      *
80      * @param initialCapacity an <code>int</code> value
81      * @return an <code>int</code> value
82      */
83     @SuppressWarnings("unchecked")
84         protected int setUp(int initialCapacity) {
85         int capacity;
86
87         capacity = super.setUp(initialCapacity);
88         _set = (BinaryQuery[])Array.newInstance(BinaryQuery.class, capacity);
89         return capacity;
90         
91     }
92
93     final protected int index(final long id) {
94
95         final BinaryQuery<Procedure>[] set = _set;
96         final int length = set.length;
97         final int hash = ((31 * ((int)(id>>>32)) + (int)id) )& 0x7fffffff;
98         int index = hash % length;
99         BinaryQuery<Procedure> cur = set[index];
100
101         if ( cur == null ) return -1;
102
103         // NOTE: here it has to be REMOVED or FULL (some user-given value)
104         if ( cur == REMOVED || !(id == cur.id)) {
105             // see Knuth, p. 529
106             final int probe = 1 + (hash % (length - 2));
107
108             do {
109                 index -= probe;
110                 if (index < 0) {
111                     index += length;
112                 }
113                 cur = set[index];
114             } while (cur != null
115                  && (cur == REMOVED || !(id == cur.id)));
116         }
117
118         return cur == null ? -1 : index;
119         
120     }
121     
122
123     /**
124      * Locates the index at which <tt>obj</tt> can be inserted.  if
125      * there is already a value equal()ing <tt>obj</tt> in the set,
126      * returns that value's index as <tt>-index - 1</tt>.
127      *
128      * @param obj an <code>Object</code> value
129      * @return the index of a FREE slot at which obj can be inserted
130      * or, if obj is already stored in the hash, the negative value of
131      * that index, minus 1: -index -1.
132      */
133     final protected int insertionIndex(final long id) {
134
135         final BinaryQuery<Procedure>[] set = _set;
136         final int length = set.length;
137         final int hash = (31 * ((int)(id>>>32)) + (int)id) & 0x7fffffff;
138         int index = hash % length;
139         BinaryQuery<Procedure> cur = set[index];
140
141         if (cur == null) {
142             return index;       // empty, all done
143         } else if (cur != REMOVED && (id == cur.id)) {
144             return -index -1;   // already stored
145         } else {                // already FULL or REMOVED, must probe
146             // compute the double hash
147             final int probe = 1 + (hash % (length - 2));
148
149             // if the slot we landed on is FULL (but not removed), probe
150             // until we find an empty slot, a REMOVED slot, or an element
151             // equal to the one we are trying to insert.
152             // finding an empty slot means that the value is not present
153             // and that we should use that slot as the insertion point;
154             // finding a REMOVED slot means that we need to keep searching,
155             // however we want to remember the offset of that REMOVED slot
156             // so we can reuse it in case a "new" insertion (i.e. not an update)
157             // is possible.
158             // finding a matching value means that we've found that our desired
159             // key is already in the table
160             if (cur != REMOVED) {
161                 // starting at the natural offset, probe until we find an
162                 // offset that isn't full.
163                 do {
164                     index -= probe;
165                     if (index < 0) {
166                         index += length;
167                     }
168                     cur = set[index];
169                 } while (cur != null
170                          && cur != REMOVED
171                          && ! (id == cur.id));
172             }
173
174             // if the index we found was removed: continue probing until we
175             // locate a free location or an element which equal()s the
176             // one we have.
177             if (cur == REMOVED) {
178                 int firstRemoved = index;
179                 while (cur != null
180                        && (cur == REMOVED || ! (id == cur.id))) {
181                     index -= probe;
182                     if (index < 0) {
183                         index += length;
184                     }
185                     cur = set[index];
186                 }
187                 // NOTE: cur cannot == REMOVED in this block
188                 return (cur != null) ? -index -1 : firstRemoved;
189             }
190             // if it's full, the key is already stored
191             // NOTE: cur cannot equal REMOVE here (would have retuned already (see above)
192             return (cur != null) ? -index -1 : index;
193         }
194     }
195
196     /**
197      * Convenience methods for subclasses to use in throwing exceptions about
198      * badly behaved user objects employed as keys.  We have to throw an
199      * IllegalArgumentException with a rather verbose message telling the
200      * user that they need to fix their object implementation to conform
201      * to the general contract for java.lang.Object.
202      *
203      * @param o1 the first of the equal elements with unequal hash codes.
204      * @param o2 the second of the equal elements with unequal hash codes.
205      * @exception IllegalArgumentException the whole point of this method.
206      */
207     protected final void throwObjectContractViolation(Object o1, Object o2)
208         throws IllegalArgumentException {
209         throw new IllegalArgumentException("Equal objects must have equal hashcodes. "
210                                            + "During rehashing, Trove discovered that "
211                                            + "the following two objects claim to be "
212                                            + "equal (as in java.lang.Object.equals()) "
213                                            + "but their hashCodes (or those calculated by "
214                                            + "your TObjectHashingStrategy) are not equal."
215                                            + "This violates the general contract of "
216                                            + "java.lang.Object.hashCode().  See bullet point two "
217                                            + "in that method's documentation. "
218                                            + "object #1 =" + o1 + " object #1 hash = " + o1.hashCode() + " object #1 id = " + System.identityHashCode(o1)
219                                            + "; object #2 =" + o2 + " object #2 hash = " + o2.hashCode() + " object #2 id = " + System.identityHashCode(o2));
220     }
221 } // TObjectHash