3

I am trying to lock a table in my testing framework in order to trigger timeouts. I am using the following code to lock the table.

String lock = "lock table "+ tableName +" in exclusive mode";
try {
        connection = DriverManager.getConnection(_url, _username, _password);
        connection.setAutoCommit(false);  
        Statement stmt1=connection.createStatement();  
        stmt1.executeUpdate(lock);  

    } catch (SQLException e) {
        e.printStackTrace();
    }

After I have executed this I try to access the page and add an element to the account. However it doesn't work, the lock doesn't seem to have occurred. Any idea why this wouldn't work? I am currently testing this in java and once I have executed that lock I am sleeping the thread while manually testing the page, could this be causing problems?

Thanks, James

1 Answer 1

9

The oracle's documentation say:

You use the LOCK TABLE statement to lock entire database tables in a specified lock mode so that you can share or deny access to them.. Row share locks allow concurrent access to a table; they prevent other users from locking the entire table for exclusive use. Table locks are released when your transaction issues a commit or rollback.

So you need to start a transaction and maintain it. The following code maintains the table locked for one minute:

String lock = "lock table "+ tableName +" in exclusive mode";
try {
    connection = DriverManager.getConnection(_url, _username, _password);
    connection.setAutoCommit(false);  
    Statement stmt1=connection.createStatement();  
    stmt1.execute(lock);  
    int i = 0;
    while (i<60) {            
        Thread.sleep(1000);    //Sleep one second
        i++;                   
    }
    connection.commit();

} catch (SQLException e) {
    connection.rollback();
    e.printStackTrace();
}
Sign up to request clarification or add additional context in comments.

4 Comments

Is there no way that I can lock it and then leave it locked until I rollback? I need to lock it while executing other java commands, and would prefer not to create a thread here.
Fair enough I guess I need to be more liberal when determining whether an answer is an 'answer'
Is this applicable in multi-thhreaded environment if each thread get a new connection object and interacts with DB
Since the lock is made in database at table level, if you have other threads accessing with new connections they must wait for table lock release.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.