Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Nested synchronization?

 
Paul Bye
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Imagine the follow code.




The problems I see are...

In readRecord1 there is a chance that another thread could delete the record inbetween the recordExists and the actual read.

If I try and rectify this problem in readRecord2 then I am synchronizing on dataFile twice.

My question is 'is synchronizing on the same object twice in this way going to cause a problem?'

An alternative would be to lock the record, which I don't really want to do for reads.

Any suggestions? Thanks
 
Seb Mathe
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My question is 'is synchronizing on the same object twice in this way going to cause a problem?'


It will not cause a problem but is it desirable ?
Is the synchronized block in 'recordExists' necessary since in readRecord2, you call recordExists from a synchronized block ?

An alternative would be to lock the record, which I don't really want to do for reads.


I don't know exactly what does your dataFile represent, but it seems you're allready "locking" all the database by using synchronized (dataFile).

An alternative could be to load all the record data (included byte flag) before checking flag validity.


And what happens when recNo is negative in your method(s) ?
 
Paul Bye
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply.

I guess I could remove the synchronized block in recordExists but then I would have to ensure that any call to recordExists occurs within a synchronized block to stop two threads trying to use the dataFile object similtaneously (dataFile is an instance of RandomAccessFile).

An alternative could be to load all the record data (included byte flag) before checking flag validity.


If I were to do this then I would end up duplicating code within all the other methods that check a record exists.

I think I'll make the recordExists method private and add a comment detailing its use.

Thanks, Paul
 
Paul Bye
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And what happens when recNo is negative in your method(s) ?


Thanks, I'd overlooked that. :roll:
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic