Debian Codegraph @

jdbm1/src/main/java/jdbm/btree/BTree.java

raw
1 /**
2 * JDBM LICENSE v1.00
3 *
4 * Redistribution and use of this software and associated documentation
5 * ("Software"), with or without modification, are permitted provided
6 * that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain copyright
9 * statements and notices. Redistributions must also contain a
10 * copy of this document.
11 *
12 * 2. Redistributions in binary form must reproduce the
13 * above copyright notice, this list of conditions and the
14 * following disclaimer in the documentation and/or other
15 * materials provided with the distribution.
16 *
17 * 3. The name "JDBM" must not be used to endorse or promote
18 * products derived from this Software without prior written
19 * permission of Cees de Groot. For written permission,
20 * please contact [email protected].
21 *
22 * 4. Products derived from this Software may not be called "JDBM"
23 * nor may "JDBM" appear in their names without prior written
24 * permission of Cees de Groot.
25 *
26 * 5. Due credit should be given to the JDBM Project
27 * (http://jdbm.sourceforge.net/).
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE JDBM PROJECT AND CONTRIBUTORS
30 * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
31 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
32 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
33 * CEES DE GROOT OR ANY CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
34 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
35 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
36 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
38 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
40 * OF THE POSSIBILITY OF SUCH DAMAGE.
41 *
42 * Copyright 2001 (C) Alex Boisvert. All Rights Reserved.
43 * Contributions are Copyright (C) 2001 by their associated contributors.
44 *
45 */
46
47 package jdbm.btree;
48
49
50 import java.io.Externalizable;
51 import java.io.IOException;
52 import java.io.ObjectInput;
53 import java.io.ObjectOutput;
54 import java.io.Serializable;
55 import java.util.Comparator;
56 import java.util.concurrent.atomic.AtomicInteger;
57
58 import jdbm.I18n;
59 import jdbm.RecordManager;
60 import jdbm.helper.Serializer;
61 import jdbm.helper.Tuple;
62 import jdbm.helper.TupleBrowser;
63
64
65 /**
66 * B+Tree persistent indexing data structure. B+Trees are optimized for
67 * block-based, random I/O storage because they store multiple keys on
68 * one tree node (called <code>BPage</code>). In addition, the leaf nodes
69 * directly contain (inline) the values associated with the keys, allowing a
70 * single (or sequential) disk read of all the values on the page.
71 * <p>
72 * B+Trees are n-airy, yeilding log(N) search cost. They are self-balancing,
73 * preventing search performance degradation when the size of the tree grows.
74 * <p>
75 * Keys and associated values must be <code>Serializable</code> objects. The
76 * user is responsible to supply a serializable <code>Comparator</code> object
77 * to be used for the ordering of entries, which are also called <code>Tuple</code>.
78 * The B+Tree allows traversing the keys in forward and reverse order using a
79 * TupleBrowser obtained from the browse() methods.
80 * <p>
81 * This implementation does not directly support duplicate keys, but it is
82 * possible to handle duplicates by inlining or referencing an object collection
83 * as a value.
84 * <p>
85 * There is no limit on key size or value size, but it is recommended to keep
86 * both as small as possible to reduce disk I/O. This is especially true for
87 * the key size, which impacts all non-leaf <code>BPage</code> objects.
88 *
89 * @author <a href="mailto:[email protected]">Alex Boisvert</a>
90 */
91 public class BTree<K, V> implements Externalizable
92 {
93 private static final boolean DEBUG = false;
94
95 /** Version id for serialization. */
96 final static long serialVersionUID = 1L;
97
98 /** Default page size (number of entries per node) */
99 public static final int DEFAULT_SIZE = 16;
100
101 /** Page manager used to persist changes in BPages */
102 protected transient RecordManager recordManager;
103
104 /** This BTree's record ID in the PageManager. */
105 private transient long recordId;
106
107 /** Comparator used to index entries. */
108 private Comparator<K> comparator;
109
110 /** Serializer used to serialize index keys (optional) */
111 protected Serializer keySerializer;
112
113 /** Serializer used to serialize index values (optional) */
114 protected Serializer valueSerializer;
115
116 /**
117 * Height of the B+Tree. This is the number of BPages you have to traverse
118 * to get to a leaf BPage, starting from the root.
119 */
120 private int bTreeHeight;
121
122 /** Record id of the root BPage */
123 private transient long rootId;
124
125 /** Number of entries in each BPage. */
126 protected int pageSize;
127
128 /** Total number of entries in the BTree */
129 protected AtomicInteger nbEntries;
130
131 /** Serializer used for BPages of this tree */
132 private transient BPage<K, V> bpageSerializer;
133
134
135 /**
136 * No-argument constructor used by serialization.
137 */
138 public BTree()
139 {
140 // empty
141 }
142
143
144 /**
145 * Create a new persistent BTree, with 16 entries per node.
146 *
147 * @param recman Record manager used for persistence.
148 * @param comparator Comparator used to order index entries
149 */
150 public BTree( RecordManager recman, Comparator<K> comparator ) throws IOException
151 {
152 createInstance( recman, comparator, null, null, DEFAULT_SIZE );
153 }
154
155
156 /**
157 * Create a new persistent BTree, with 16 entries per node.
158 *
159 * @param recman Record manager used for persistence.
160 * @param keySerializer Serializer used to serialize index keys (optional)
161 * @param valueSerializer Serializer used to serialize index values (optional)
162 * @param comparator Comparator used to order index entries
163 */
164 public BTree( RecordManager recman, Comparator<K> comparator, Serializer keySerializer,
165 Serializer valueSerializer ) throws IOException
166 {
167 createInstance( recman, comparator, keySerializer, valueSerializer, DEFAULT_SIZE );
168 }
169
170
171 /**
172 * Create a new persistent BTree with the given number of entries per node.
173 *
174 * @param recman Record manager used for persistence.
175 * @param comparator Comparator used to order index entries
176 * @param keySerializer Serializer used to serialize index keys (optional)
177 * @param valueSerializer Serializer used to serialize index values (optional)
178 * @param pageSize Number of entries per page (must be even).
179 */
180 public BTree( RecordManager recman, Comparator<K> comparator, Serializer keySerializer,
181 Serializer valueSerializer, int pageSize ) throws IOException
182 {
183 createInstance( recman, comparator, keySerializer, valueSerializer, pageSize );
184 }
185
186
187 /**
188 * The real BTree constructor.
189 */
190 private void createInstance( RecordManager recordManager, Comparator<K> comparator, Serializer keySerializer,
191 Serializer valueSerializer, int pageSize ) throws IOException
192 {
193 if ( recordManager == null )
194 {
195 throw new IllegalArgumentException( I18n.err( I18n.ERR_517 ) );
196 }
197
198 if ( comparator == null )
199 {
200 throw new IllegalArgumentException( I18n.err( I18n.ERR_518 ) );
201 }
202
203 if ( !( comparator instanceof Serializable ) )
204 {
205 throw new IllegalArgumentException( I18n.err( I18n.ERR_519 ) );
206 }
207
208 // make sure there's an even number of entries per BPage
209 if ( ( pageSize & 1 ) != 0 )
210 {
211 throw new IllegalArgumentException( I18n.err( I18n.ERR_522 ) );
212 }
213
214 this.recordManager = recordManager;
215 this.comparator = comparator;
216 this.keySerializer = keySerializer;
217 this.valueSerializer = valueSerializer;
218 this.pageSize = pageSize;
219 this.bpageSerializer = new BPage<K, V>();
220 this.bpageSerializer.btree = this;
221 this.nbEntries = new AtomicInteger( 0 );
222
223 this.recordId = recordManager.insert( this );
224 }
225
226
227 public void setPageSize( int pageSize )
228 {
229 if ( ( pageSize & 0x0001 ) != 0 )
230 {
231 this.pageSize = DEFAULT_SIZE;
232 }
233 else
234 {
235 this.pageSize = pageSize;
236 }
237 }
238
239
240 /**
241 * Load a persistent BTree.
242 *
243 * @param recman RecordManager used to store the persistent btree
244 * @param recid Record id of the BTree
245 */
246 public BTree<K, V> load( RecordManager recman, long recid ) throws IOException
247 {
248 BTree<K, V> btree = ( BTree<K, V> ) recman.fetch( recid );
249 btree.recordId = recid;
250 btree.recordManager = recman;
251 btree.bpageSerializer = new BPage<K, V>();
252 btree.bpageSerializer.btree = btree;
253
254 return btree;
255 }
256
257
258 /**
259 * Insert an entry in the BTree.
260 * <p>
261 * The BTree cannot store duplicate entries. An existing entry can be
262 * replaced using the <code>replace</code> flag. If an entry with the
263 * same key already exists in the BTree, its value is returned.
264 *
265 * @param key Insert key
266 * @param value Insert value
267 * @param replace Set to true to replace an existing key-value pair.
268 * @return Existing value, if any.
269 */
270 public synchronized Object insert( K key, V value, boolean replace ) throws IOException
271 {
272 if ( key == null )
273 {
274 throw new IllegalArgumentException( I18n.err( I18n.ERR_523 ) );
275 }
276
277 if ( value == null )
278 {
279 throw new IllegalArgumentException( I18n.err( I18n.ERR_524 ) );
280 }
281
282 BPage<K, V> rootPage = getRoot();
283
284 if ( rootPage == null )
285 {
286 // BTree is currently empty, create a new root BPage
287 if ( DEBUG )
288 {
289 System.out.println( "BTree.insert() new root BPage" );
290 }
291
292 rootPage = new BPage<K, V>( this, key, value );
293 rootId = rootPage.getRecordId();
294 bTreeHeight = 1;
295 nbEntries.set( 1 );
296 recordManager.update( recordId, this );
297
298 return null;
299 }
300 else
301 {
302 BPage.InsertResult<K, V> insert = rootPage.insert( bTreeHeight, key, value, replace );
303 boolean dirty = false;
304
305 if ( insert.overflow != null )
306 {
307 // current root page overflowed, we replace with a new root page
308 if ( DEBUG )
309 {
310 System.out.println( "BTree.insert() replace root BPage due to overflow" );
311 }
312
313 rootPage = new BPage<K, V>( this, rootPage, insert.overflow );
314 rootId = rootPage.getRecordId();
315 bTreeHeight += 1;
316 dirty = true;
317 }
318
319 if ( insert.existing == null )
320 {
321 nbEntries.getAndIncrement();
322 dirty = true;
323 }
324
325 if ( dirty )
326 {
327 recordManager.update( recordId, this );
328 }
329
330 // insert might have returned an existing value
331 return insert.existing;
332 }
333 }
334
335
336 /**
337 * Remove an entry with the given key from the BTree.
338 *
339 * @param key Removal key
340 * @return Value associated with the key, or null if no entry with given
341 * key existed in the BTree.
342 */
343 public synchronized V remove( K key ) throws IOException
344 {
345 if ( key == null )
346 {
347 throw new IllegalArgumentException( I18n.err( I18n.ERR_523 ) );
348 }
349
350 BPage<K, V> rootPage = getRoot();
351
352 if ( rootPage == null )
353 {
354 return null;
355 }
356
357 boolean dirty = false;
358 BPage.RemoveResult<V> remove = rootPage.remove( bTreeHeight, key );
359
360 if ( remove.underflow && rootPage.isEmpty() )
361 {
362 bTreeHeight -= 1;
363 dirty = true;
364
365 recordManager.delete( rootId );
366
367 if ( bTreeHeight == 0 )
368 {
369 rootId = 0;
370 }
371 else
372 {
373 rootId = rootPage.childBPage( pageSize - 1 ).getRecordId();
374 }
375 }
376
377 if ( remove.value != null )
378 {
379 nbEntries.getAndDecrement();
380 dirty = true;
381 }
382
383 if ( dirty )
384 {
385 recordManager.update( recordId, this );
386 }
387
388 return remove.value;
389 }
390
391
392 /**
393 * Find the value associated with the given key.
394 *
395 * @param key Lookup key.
396 * @return Value associated with the key, or null if not found.
397 */
398 public synchronized V find( K key ) throws IOException
399 {
400 if ( key == null )
401 {
402 throw new IllegalArgumentException( I18n.err( I18n.ERR_523 ) );
403 }
404
405 BPage<K, V> rootPage = getRoot();
406
407 if ( rootPage == null )
408 {
409 return null;
410 }
411
412 Tuple<K, V> tuple = new Tuple<K, V>( null, null );
413 TupleBrowser<K, V> browser = rootPage.find( bTreeHeight, key );
414
415 if ( browser.getNext( tuple ) )
416 {
417 // find returns the matching key or the next ordered key, so we must
418 // check if we have an exact match
419 if ( comparator.compare( key, tuple.getKey() ) != 0 )
420 {
421 return null;
422 }
423 else
424 {
425 return tuple.getValue();
426 }
427 }
428 else
429 {
430 return null;
431 }
432 }
433
434
435 /**
436 * Find the value associated with the given key, or the entry immediately
437 * following this key in the ordered BTree.
438 *
439 * @param key Lookup key.
440 * @return Value associated with the key, or a greater entry, or null if no
441 * greater entry was found.
442 */
443 public synchronized Tuple<K, V> findGreaterOrEqual( K key ) throws IOException
444 {
445 Tuple<K, V> tuple;
446 TupleBrowser<K, V> browser;
447
448 if ( key == null )
449 {
450 // there can't be a key greater than or equal to "null"
451 // because null is considered an infinite key.
452 return null;
453 }
454
455 tuple = new Tuple<K, V>( null, null );
456 browser = browse( key );
457
458 if ( browser.getNext( tuple ) )
459 {
460 return tuple;
461 }
462 else
463 {
464 return null;
465 }
466 }
467
468
469 /**
470 * Get a browser initially positioned at the beginning of the BTree.
471 * <p><b>
472 * WARNING: If you make structural modifications to the BTree during
473 * browsing, you will get inconsistent browing results.
474 * </b>
475 *
476 * @return Browser positionned at the beginning of the BTree.
477 */
478 public synchronized TupleBrowser<K, V> browse() throws IOException
479 {
480 BPage<K, V> rootPage = getRoot();
481
482 if ( rootPage == null )
483 {
484 return new EmptyBrowser()
485 {
486 };
487 }
488
489 TupleBrowser<K, V> browser = rootPage.findFirst();
490
491 return browser;
492 }
493
494
495 /**
496 * Get a browser initially positioned just before the given key.
497 * <p><b>
498 * WARNING: If you make structural modifications to the BTree during
499 * browsing, you will get inconsistent browsing results.
500 * </b>
501 *
502 * @param key Key used to position the browser. If null, the browser
503 * will be positioned after the last entry of the BTree.
504 * (Null is considered to be an "infinite" key)
505 * @return Browser positioned just before the given key.
506 */
507 public synchronized TupleBrowser<K, V> browse( K key ) throws IOException
508 {
509 BPage<K, V> rootPage = getRoot();
510
511 if ( rootPage == null )
512 {
513 return new EmptyBrowser()
514 {
515 };
516 }
517
518 TupleBrowser<K, V> browser = rootPage.find( bTreeHeight, key );
519
520 return browser;
521 }
522
523
524 /**
525 * Return the number of entries (size) of the BTree.
526 */
527 public int size()
528 {
529 return nbEntries.get();
530 }
531
532
533 /**
534 * Return the persistent record identifier of the BTree.
535 */
536 public long getRecordId()
537 {
538 return recordId;
539 }
540
541
542 /**
543 * Return the root BPage<Object, Object>, or null if it doesn't exist.
544 */
545 private BPage<K, V> getRoot() throws IOException
546 {
547 if ( rootId == 0 )
548 {
549 return null;
550 }
551
552 BPage<K, V> root = ( BPage<K, V> ) recordManager.fetch( rootId, bpageSerializer );
553 root.setRecordId( rootId );
554 root.btree = this;
555
556 return root;
557 }
558
559
560 /**
561 * Implement Externalizable interface.
562 */
563 public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException
564 {
565 comparator = ( Comparator<K> ) in.readObject();
566 keySerializer = ( Serializer ) in.readObject();
567 valueSerializer = ( Serializer ) in.readObject();
568 bTreeHeight = in.readInt();
569 rootId = in.readLong();
570 pageSize = in.readInt();
571 nbEntries = new AtomicInteger( in.readInt() );
572 }
573
574
575 /**
576 * Implement Externalizable interface.
577 */
578 public void writeExternal( ObjectOutput out ) throws IOException
579 {
580 out.writeObject( comparator );
581 out.writeObject( keySerializer );
582 out.writeObject( valueSerializer );
583 out.writeInt( bTreeHeight );
584 out.writeLong( rootId );
585 out.writeInt( pageSize );
586 out.writeInt( nbEntries.get() );
587 }
588
589
590 public void setValueSerializer( Serializer valueSerializer )
591 {
592 this.valueSerializer = valueSerializer;
593 }
594
595 /** PRIVATE INNER CLASS
596 * Browser returning no element.
597 */
598 class EmptyBrowser extends TupleBrowser<K, V>
599 {
600 public boolean getNext( Tuple<K, V> tuple )
601 {
602 return false;
603 }
604
605
606 public boolean getPrevious( Tuple<K, V> tuple )
607 {
608 return false;
609 }
610 }
611
612
613 /**
614 * @return the comparator
615 */
616 public Comparator<K> getComparator()
617 {
618 return comparator;
619 }
620
621
622 public String toString()
623 {
624 StringBuilder sb = new StringBuilder();
625
626 sb.append( "BTree" );
627 sb.append( "(height:" ).append( bTreeHeight );
628 sb.append( ", pageSize:" ).append( pageSize );
629 sb.append( ", nbEntries:" ).append( nbEntries );
630 sb.append( ", rootId:" ).append( rootId );
631 sb.append( ", comparator:" );
632
633 if ( comparator == null )
634 {
635 sb.append( "null" );
636 }
637 else
638 {
639 sb.append( comparator.getClass().getSimpleName() );
640 }
641
642 sb.append( ", keySerializer:" );
643
644 if ( keySerializer == null )
645 {
646 sb.append( "null" );
647 }
648 else
649 {
650 sb.append( keySerializer.getClass().getSimpleName() );
651 }
652
653 sb.append( ", valueSerializer:" );
654
655 if ( valueSerializer == null )
656 {
657 sb.append( "null" );
658 }
659 else
660 {
661 sb.append( valueSerializer.getClass().getSimpleName() );
662 }
663
664 sb.append( ")\n" );
665
666 return sb.toString();
667 }
668 }