1

I am new to Hibernate this is my first post in the stackoverflow. I am using Hibernate 3.3.2 GA and MySql as a DB.

Here is my question:

I am reading the record for the DB table which is having status='N'.

List sendSmsPropertiesList=hbSession.createQuery("from TSendSms where status='N' ").setMaxResults(1).list();

I have 2 threads accessing the same table using above sql to fetch the record from the DB with status='N'(for example if there are 3 records with status='N', first thread should fetch first record and second thread should fetch the second record). But both are fetching same record(First record). Here i need to have a lock on the table row once it is fetched by one thread, when second thread comes then it should go to the second row.

Could you please help me with the above example?

Thanks in advance.

anil
  • 11
  • 3
  • A lock doesn't hide a row. It blocks a thread until the lock is released. From what you describe, you don't want a lock. – JB Nizet Sep 18 '14 at 10:19
  • Hi JB Nizet, Yes it should block the other threads to read that row till the current thread completes its transaction. – anil Sep 18 '14 at 11:24
  • http://docs.jboss.org/hibernate/orm/4.1/javadocs/org/hibernate/Query.html#setLockMode(java.lang.String, org.hibernate.LockMode) – JB Nizet Sep 18 '14 at 11:37
  • Thanks JB Nizet. I tried with setLockMode method but this is not suitable for my requirement. And the setLockOptions method is avilable form the version 3.5. Here my project restricts to use 3.3 version. – anil Sep 18 '14 at 12:21

1 Answers1

-1

Modify the status to 'Y' or update it somewhere so that same record would be process . As it seems from the code and the best way it to update the status that it is processed if you can not modify it then add a new column for the same.

nirajkumar
  • 335
  • 1
  • 3
  • 14
  • Thanks Nirajkumar. I have to update the record status to 'Y' only once it get processed. It is processing twice as it is fetching by both the threads. – anil Sep 18 '14 at 10:25
  • Hi Nirajkumar, Any way i am updating the status to 'Y' after the record processed. Here the record is accessing by two threads before updating the status to 'Y'. It should allow only one thread to work on one record. – anil Sep 18 '14 at 12:13
  • hi Nirajkumar, Is it possible to post the example using pthread_mutex_lock in java. – anil Sep 18 '14 at 12:40
  • Anil you can refer http://stackoverflow.com/questions/5291041/is-there-a-mutex-in-java and http://www.oracle.com/technetwork/articles/javase/index-140767.html for mutex lock – nirajkumar Sep 18 '14 at 14:31
  • Nirajkumar, Just realized mutex lock is just blocking the code to access by different threads at a time. That means that only one thread at a time (Then there is no point to use multiple threads we can achieve same thing with single thread also.). I think it is better to lock the db row using hibernate. – anil Sep 19 '14 at 09:34