Syncronised vs Auto Commit...

I have a static method which increments a number in a database then selects it, this method is used by multiple threads.

public static synchronized int getNextNumber(Connection con)throws SQLException

{

con.setAutoCommit( false );

try

{

//create statment

//increment number

//select number

con.commit();

con.setAutoCommit( true );

return number;

}

catch( SQLException sqe )

{

con.rollback();

con.setAutoCommit( true );

throw sqe;

}

}

My question: Is the syncronised necessary or will the commit control prevent 2 threads running the critical section of this code at the same time?

[728 byte] By [samlewis23] at [2007-9-26 3:55:27]
# 1
how ur incrementing the number in a database?Fact is..u have to synchronize the method if multiple threads are accesing same data at same time
psvinayram at 2007-6-29 12:45:32 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 2
I am incrementing the number using Statments executeUpdate() method.The SQL is "UPDATE MYDB.MYTABLE SET NUM=NUM+1 WHERE PARAMETER='MYNUMBER' "
samlewis23 at 2007-6-29 12:45:32 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 3

> I have a static method which increments a number in a

> database then selects it, this method is used by

> multiple threads.

>

> public static synchronized int

> getNextNumber(Connection con)throws SQLException

> {

> con.setAutoCommit( false );

> try

> {

> //create statment

>

> //increment number

>

> //select number

>

> con.commit();

> con.setAutoCommit( true );

> return number;

> }

> catch( SQLException sqe )

> {

> con.rollback();

> con.setAutoCommit( true );

> throw sqe;

> }

> }

>

> My question: Is the syncronised necessary or will the

> commit control prevent 2 threads running the critical

> section of this code at the same time?

Hello,

You must use synchronized because from the database point of view, if one thread makes the select, the value returned will be for example 1. The second thread makes its select and receives 1 too. But meanwhile, the thread 1 update the number to 2 and commit. When the thread2 updates the number, it will apply a value of 2 which is wrong, it should be 3. By synchronizing your method, you prevent such a wrong result.

Another method is to use "select for update" but I'm not really sure because it's on Oracle and I wonder if it's real SQL. If you can use it, the commit of the second thread will throw an SQLException because the database engine knows that since your select, the value changed.

Anyway, I suggest you to use synchronized on the method or on a portion of your code by using a lock object.

Hope it helps.

Fred

praca at 2007-6-29 12:45:32 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...