CachedIoAdapter Example

Let's look on an example at the benefits of CachedIoAdapter.

We will use the following methods to initiate write and read from a database file:

CachedIOExample.java: setObjects
01public static void setObjects(){ 02 new File(YAPFILENAME).delete(); 03 ObjectContainer db = Db4o.openFile(YAPFILENAME); 04 try { 05 long t1 = System.currentTimeMillis(); 06 for (int i = 0; i< 50000; i++){ 07 Pilot pilot = new Pilot("Pilot #"+i); 08 db.set(pilot); 09 } 10 long t2 = System.currentTimeMillis(); 11 long timeElapsed = t2 - t1; 12 System.out.println("Time elapsed for setting objects ="+ timeElapsed + " ms"); 13 t1 = System.currentTimeMillis(); 14 db.commit(); 15 t2 = System.currentTimeMillis(); 16 timeElapsed = t2 - t1; 17 System.out.println("Time elapsed for commit =" + timeElapsed + " ms"); 18 } finally { 19 db.close(); 20 } 21 }
CachedIOExample.java: getObjects
01public static void getObjects(){ 02 03 ObjectContainer db = Db4o.openFile(YAPFILENAME); 04 try { 05 long t1 = System.currentTimeMillis(); 06 ObjectSet result=db.get(null); 07 long t2 = System.currentTimeMillis(); 08 long timeElapsed = t2 - t1; 09 System.out.println("Time elapsed for the query ="+ timeElapsed + " ms"); 10 System.out.println("Objects in the database: " + result.size()); 11 } finally { 12 db.close(); 13 } 14 }

Try to execute the code with the default settings and write down the results. Then configure CachedIoAdapter using the code below and test the performance again:

CachedIOExample.java: configureCache
1public static void configureCache(){ 2 System.out.println("Setting up cached io adapter"); 3 // new cached IO adapter with 256 pages 1024 bytes each 4 CachedIoAdapter adapter = new CachedIoAdapter(new RandomAccessFileAdapter(), 1024, 256); 5 Db4o.configure().io(adapter); 6 }

The performance delta will be more significant for more objects and bigger cache memory.