FileDocCategorySizeDatePackage
DatabaseLockTest.javaAPI DocAndroid 1.5 API5949Wed May 06 22:42:02 BST 2009com.android.unit_tests

DatabaseLockTest

public class DatabaseLockTest extends android.test.AndroidTestCase

Fields Summary
private static final int
NUM_ITERATIONS
private static final int
SLEEP_TIME
private static final int
MAX_ALLOWED_LATENCY_TIME
private android.database.sqlite.SQLiteDatabase
mDatabase
private File
mDatabaseFile
private AtomicInteger
mCounter
Constructors Summary
Methods Summary
protected voidsetUp()


    
         
        super.setUp();
        File parentDir = getContext().getFilesDir();
        mDatabaseFile = new File(parentDir, "database_test.db");
        
        if (mDatabaseFile.exists()) {
            mDatabaseFile.delete();
        }
        mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null);
        assertNotNull(mDatabase);
    
private voidstartDatabaseFairnessThread()

        Thread thread = new DatabaseFairnessThread();
        thread.start();
    
private voidstartDatabaseLatencyThread()

        Thread thread = new DatabaseLatencyThread();
        thread.start();
    
protected voidtearDown()

        mDatabase.close();
        mDatabaseFile.delete();
        super.tearDown();
    
public voidtestLockFairness()

        startDatabaseFairnessThread();
        int previous = 0;
        for (int i = 0; i < NUM_ITERATIONS; i++) { 
            mDatabase.beginTransaction();
            int val = mCounter.get();
            if (i == 0) {
                previous = val - i;
            }
            assertTrue(previous == (val - i));
            try {
                Thread.currentThread().sleep(SLEEP_TIME); 
            } catch (InterruptedException e) {
                // ignore
            }
            mDatabase.endTransaction();
        }
    
public voidtestLockLatency()

        startDatabaseLatencyThread();
        int previous = 0;
        long sumTime = 0;
        long maxTime = 0;
        for (int i = 0; i < NUM_ITERATIONS; i++) { 
            long startTime = System.currentTimeMillis();
            mDatabase.beginTransaction();
            long endTime = System.currentTimeMillis();
            long elapsedTime = endTime - startTime;
            if (maxTime < elapsedTime) {
                maxTime = elapsedTime;
            }
            sumTime += elapsedTime;
            try {
                Thread.currentThread().sleep(SLEEP_TIME); 
            } catch (InterruptedException e) {
                // ignore
            }   
            mDatabase.endTransaction();
        }
        long averageTime = sumTime/NUM_ITERATIONS;
        Log.i("DatabaseLockLatency", "AverageTime: " + averageTime);
        Log.i("DatabaseLockLatency", "MaxTime: " + maxTime);
        assertTrue( (averageTime - SLEEP_TIME) <= MAX_ALLOWED_LATENCY_TIME);