1

In my spring-hibernate application which has active-mq as well, multiple consumers in the same time access one of the method which provides persistence for logging objects to mysql db for us. Due to the concurrency access of that method, the logic I coded in it fails in some cases. I 'm sharing the logic below:

// check the current sourceId whether is included or not in log table
List<MyLogObject> logs = logService.findBySourceId(currentSourceId); 

if(logs.size() == 0){
  logService.persist(currentLogObject);
}

As you see, if the multiple consumers access this code block in the same time, the size of log should return 0 for them and thus they persist the same object twice or more.

How can I avoid multiple persistence of an object in case of active-mq and multiple consumer usage.

Is it possible to achieve that by using syncronized feature of java?

Thanks in advance.

javatar
  • 4,542
  • 14
  • 50
  • 67

1 Answers1

1

Yes, I think having a lock here and using synchronized on that lock should really work if the object that contains this logging method is shared among many Threads.

It should be as simple as :

class YourClass{
    .....
Object monitor = new Object();

public void log(){

    synchronized(monitor){
    .....

    }
}
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Thanks at first place. Can you please explain more in detail about monitor object? I am confused of the difference between synchronized(this) and synchronized(anObject), what are the differences between them, when should we avoid or prefer to use any of them? Thanks again. – javatar Jan 31 '12 at 14:00
  • @Bariscan np, glad I could help. The thing is that you probably should always NOT do synchronized(this). See these two: http://stackoverflow.com/questions/442564/avoid-synchronizedthis-in-java and http://stackoverflow.com/questions/416183/in-java-critical-sections-what-should-i-synchronize-on, they explain way better then me – Eugene Jan 31 '12 at 15:16