Debian Codegraph @

jdbm1/src/main/java/jdbm/recman/RecordFile.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 2000 (C) Cees de Groot. All Rights Reserved.
43 * Contributions are Copyright (C) 2000 by their associated contributors.
44 *
45 * $Id: RecordFile.java,v 1.6 2005/06/25 23:12:32 doomdark Exp $
46 */
47 package jdbm.recman;
48
49
50 import java.io.IOException;
51 import java.io.RandomAccessFile;
52 import java.util.HashMap;
53 import java.util.Iterator;
54 import java.util.LinkedList;
55
56 import jdbm.I18n;
57
58
59 /**
60 * This class represents a random access file as a set of fixed size
61 * records. Each record has a physical record number, and records are
62 * cached in order to improve access.
63 *<p>
64 * The set of dirty records on the in-use list constitutes a transaction.
65 * Later on, we will send these records to some recovery thingy.
66 */
67 public final class RecordFile
68 {
69 private TransactionManager transactionManager;
70
71 // state transitions: free -> inUse -> dirty -> inTxn -> free
72 // free is a cache, thus a FIFO. The rest are hashes.
73 private final LinkedList<BlockIo> free = new LinkedList<BlockIo>();
74 private final HashMap<Long, BlockIo> inUse = new HashMap<Long, BlockIo>();
75 private final HashMap<Long, BlockIo> dirty = new HashMap<Long, BlockIo>();
76 private final HashMap<Long, BlockIo> inTxn = new HashMap<Long, BlockIo>();
77
78 // transactions disabled?
79 private boolean transactionsDisabled = false;
80
81 /** The length of a single block. */
82 public final static int BLOCK_SIZE = 8192;//4096;
83
84 /** The extension of a record file */
85 final static String extension = ".db";
86
87 /** A block of clean data to wipe clean pages. */
88 final static byte[] cleanData = new byte[BLOCK_SIZE];
89
90 private RandomAccessFile file;
91 private final String fileName;
92
93
94 /**
95 * Creates a new object on the indicated filename. The file is
96 * opened in read/write mode.
97 *
98 * @param fileName the name of the file to open or create, without
99 * an extension.
100 * @throws IOException whenever the creation of the underlying
101 * RandomAccessFile throws it.
102 */
103 RecordFile( String fileName ) throws IOException
104 {
105 this.fileName = fileName;
106 file = new RandomAccessFile( fileName + extension, "rw" );
107 }
108
109
110 TransactionManager getTxnMgr() throws IOException
111 {
112 if ( transactionsDisabled )
113 {
114 throw new IllegalStateException( "Transactions are disabled." );
115 }
116 if ( transactionManager == null )
117 {
118 transactionManager = new TransactionManager( this );
119 }
120 return transactionManager;
121 }
122
123
124 /**
125 * Returns the file name.
126 */
127 String getFileName()
128 {
129 return fileName;
130 }
131
132
133 /**
134 * Disables transactions: doesn't sync and doesn't use the
135 * transaction manager.
136 */
137 void disableTransactions()
138 {
139 transactionsDisabled = true;
140 }
141
142
143 /**
144 * Gets a block from the file. The returned byte array is the in-memory
145 * copy of the record, and thus can be written (and subsequently released
146 * with a dirty flag in order to write the block back).
147 *
148 * @param blockid The record number to retrieve.
149 */
150 BlockIo get( long blockid ) throws IOException
151 {
152 // try in transaction list, dirty list, free list
153
154 BlockIo node = inTxn.get( blockid );
155 if ( node != null )
156 {
157 inTxn.remove( blockid );
158 inUse.put( blockid, node );
159 return node;
160 }
161
162 node = dirty.get( blockid );
163 if ( node != null )
164 {
165 dirty.remove( blockid );
166 inUse.put( blockid, node );
167 return node;
168 }
169
170 for ( Iterator<BlockIo> i = free.iterator(); i.hasNext(); )
171 {
172 BlockIo cur = i.next();
173 if ( cur.getBlockId() == blockid )
174 {
175 node = cur;
176 i.remove();
177 inUse.put( blockid, node );
178 return node;
179 }
180 }
181
182 // sanity check: can't be on in use list
183 if ( inUse.get( blockid ) != null )
184 {
185 throw new Error( I18n.err( I18n.ERR_554, blockid ) );
186 }
187
188 // get a new node and read it from the file
189 node = getNewNode( blockid );
190 long offset = blockid * BLOCK_SIZE;
191 if ( file.length() > 0 && offset <= file.length() )
192 {
193 read( file, offset, node.getData(), BLOCK_SIZE );
194 }
195 else
196 {
197 System.arraycopy( cleanData, 0, node.getData(), 0, BLOCK_SIZE );
198 }
199
200 inUse.put( blockid, node );
201 node.setClean();
202 return node;
203 }
204
205
206 /**
207 * Releases a block.
208 *
209 * @param blockid The record number to release.
210 * @param isDirty If true, the block was modified since the get().
211 */
212 void release( long blockid, boolean isDirty ) throws IOException
213 {
214 BlockIo node = inUse.get( blockid );
215
216 if ( node == null )
217 {
218 throw new IOException( I18n.err( I18n.ERR_555, blockid ) );
219 }
220
221 if ( !node.isDirty() && isDirty )
222 {
223 node.setDirty();
224 }
225
226 release( node );
227 }
228
229
230 /**
231 * Releases a block.
232 *
233 * @param block The block to release.
234 */
235 void release( BlockIo block )
236 {
237 inUse.remove( block.getBlockId() );
238
239 if ( block.isDirty() )
240 {
241 // System.out.println( "Dirty: " + key + block );
242 dirty.put( block.getBlockId(), block );
243 }
244 else
245 {
246 if ( !transactionsDisabled && block.isInTransaction() )
247 {
248 inTxn.put( block.getBlockId(), block );
249 }
250 else
251 {
252 free.add( block );
253 }
254 }
255 }
256
257
258 /**
259 * Discards a block (will not write the block even if it's dirty)
260 *
261 * @param block The block to discard.
262 */
263 void discard( BlockIo block )
264 {
265 inUse.remove( block.getBlockId() );
266
267 // note: block not added to free list on purpose, because
268 // it's considered invalid
269 }
270
271
272 /**
273 * Commits the current transaction by flushing all dirty buffers to disk.
274 */
275 void commit() throws IOException
276 {
277 // debugging...
278 if ( !inUse.isEmpty() && inUse.size() > 1 )
279 {
280 showList( inUse.values().iterator() );
281 throw new Error( I18n.err( I18n.ERR_556, inUse.size() ) );
282 }
283
284 // System.out.println("committing...");
285
286 if ( dirty.size() == 0 )
287 {
288 // if no dirty blocks, skip commit process
289 return;
290 }
291
292 if ( !transactionsDisabled )
293 {
294 getTxnMgr().start();
295 }
296
297 for ( Iterator<BlockIo> i = dirty.values().iterator(); i.hasNext(); )
298 {
299 BlockIo node = i.next();
300 i.remove();
301
302 // System.out.println("node " + node + " map size now " + dirty.size());
303 if ( transactionsDisabled )
304 {
305 long offset = node.getBlockId() * BLOCK_SIZE;
306 file.seek( offset );
307 file.write( node.getData() );
308 node.setClean();
309 free.add( node );
310 }
311 else
312 {
313 getTxnMgr().add( node );
314 inTxn.put( node.getBlockId(), node );
315 }
316 }
317
318 if ( !transactionsDisabled )
319 {
320 getTxnMgr().commit();
321 }
322 }
323
324
325 /**
326 * Rollback the current transaction by discarding all dirty buffers
327 */
328 void rollback() throws IOException
329 {
330 // debugging...
331 if ( !inUse.isEmpty() )
332 {
333 showList( inUse.values().iterator() );
334 throw new Error( I18n.err( I18n.ERR_557, inUse.size() ) );
335 }
336
337 // System.out.println("rollback...");
338 dirty.clear();
339
340 if ( !transactionsDisabled )
341 {
342 getTxnMgr().synchronizeLogFromDisk();
343 }
344
345 if ( !inTxn.isEmpty() )
346 {
347 showList( inTxn.values().iterator() );
348 throw new Error( I18n.err( I18n.ERR_558, inTxn.size() ) );
349 }
350 }
351
352
353 /**
354 * Commits and closes file.
355 */
356 void close() throws IOException
357 {
358 if ( !dirty.isEmpty() )
359 {
360 commit();
361 }
362
363 if ( !transactionsDisabled )
364 {
365 getTxnMgr().shutdown();
366 }
367
368 if ( !inTxn.isEmpty() )
369 {
370 showList( inTxn.values().iterator() );
371 throw new Error( I18n.err( I18n.ERR_559 ) );
372 }
373
374 // these actually ain't that bad in a production release
375 if ( !dirty.isEmpty() )
376 {
377 System.out.println( "ERROR: dirty blocks at close time" );
378 showList( dirty.values().iterator() );
379 throw new Error( I18n.err( I18n.ERR_560 ) );
380 }
381
382 if ( !inUse.isEmpty() )
383 {
384 System.out.println( "ERROR: inUse blocks at close time" );
385 showList( inUse.values().iterator() );
386 throw new Error( I18n.err( I18n.ERR_561 ) );
387 }
388
389 // debugging stuff to keep an eye on the free list
390 // System.out.println("Free list size:" + free.size());
391 file.close();
392 file = null;
393 }
394
395
396 /**
397 * Force closing the file and underlying transaction manager.
398 * Used for testing purposed only.
399 */
400 void forceClose() throws IOException
401 {
402 if ( !transactionsDisabled )
403 {
404 getTxnMgr().forceClose();
405 }
406 file.close();
407 }
408
409
410 /**
411 * Prints contents of a list
412 */
413 private void showList( Iterator<BlockIo> i )
414 {
415 int cnt = 0;
416 while ( i.hasNext() )
417 {
418 System.out.println( "elem " + cnt + ": " + i.next() );
419 cnt++;
420 }
421 }
422
423
424 /**
425 * Returns a new node. The node is retrieved (and removed) from the
426 * released list or created new.
427 */
428 private BlockIo getNewNode( long blockid ) throws IOException
429 {
430 BlockIo retval = null;
431
432 if ( !free.isEmpty() )
433 {
434 retval = free.removeFirst();
435 }
436
437 if ( retval == null )
438 {
439 retval = new BlockIo( 0, new byte[BLOCK_SIZE] );
440 }
441
442 retval.setBlockId( blockid );
443 retval.setView( null );
444 return retval;
445 }
446
447
448 /**
449 * Synchronizes a node to disk. This is called by the transaction manager's
450 * synchronization code.
451 */
452 void synch( BlockIo node ) throws IOException
453 {
454 byte[] data = node.getData();
455 if ( data != null )
456 {
457 long offset = node.getBlockId() * BLOCK_SIZE;
458 file.seek( offset );
459 file.write( data );
460 }
461 }
462
463
464 /**
465 * Releases a node from the transaction list, if it was sitting there.
466 *
467 * @param recycle true if block data can be reused
468 */
469 void releaseFromTransaction( BlockIo node, boolean recycle ) throws IOException
470 {
471 if ( ( inTxn.remove( node.getBlockId() ) != null ) && recycle )
472 {
473 free.add( node );
474 }
475 }
476
477
478 /**
479 * Synchronizes the file.
480 */
481 void sync() throws IOException
482 {
483 file.getFD().sync();
484 }
485
486
487 /**
488 * Utility method: Read a block from a RandomAccessFile
489 */
490 private static void read( RandomAccessFile file, long offset, byte[] buffer, int nBytes ) throws IOException
491 {
492 file.seek( offset );
493 int remaining = nBytes;
494 int pos = 0;
495 while ( remaining > 0 )
496 {
497 int read = file.read( buffer, pos, remaining );
498 if ( read == -1 )
499 {
500 System.arraycopy( cleanData, 0, buffer, pos, remaining );
501 break;
502 }
503 remaining -= read;
504 pos += read;
505 }
506 }
507 }