• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Nested synchronized for raf

 
Steve Taiwan
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have these 3 methods.

Before creating a new record, I want to read all records in
db file to check if there is a duplicate key. And I hope to do all things at one time.
Due to this reason, my RandomAccessFile instance is nested in at least 3 synchronized block.
Is the code OK?
 
Hanna Habashy
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Steve,
You might want to consider to synchronize the data access methods instead of synchronizing on an instance.
 
Steve Taiwan
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Hanna.

I change the signature of 3 method. I pass raf to other methods. Would you mind taking a look at them?
Thanks.

 
Hanna Habashy
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Steve,
I don't see anything wrong with your methods. However, you might want to think about performance if you care about it. I understood from your code that all data access methods are using the same static RAF..Correct me if I misunderstand.
If my assumption is correct, and every data access method synchronize on the same RAF object, then only one thread will be able to access the data at the same time. If that what you want your code do, then that is fine.
However, you should think about the bottle neck in performance. In your design, no two threads can search, or read at the same time...!
 
Steve Taiwan
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Hanna.

You are so smart. I do want that no two threads can search or read at the same time. If thread A is using RAF to point to RecNo1 and thread B is also using RAF to point to RecNo2, both thread A and B could be reading wrong data.

One more question, what's wrong with my OLD CODE???
 
Hanna Habashy
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Steve,
I don't see anything wrong with the first code. You synchronized the same object RAF 3 times, which is no neccessarly. The first method will obtain the lock and then pass it to the second and third method. If you don't synchronize on the second and the third method, it will not make difference, because you syncronized the block they are called from.

I hope I am making sense.
 
Steve Taiwan
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Hanna.

Thank you so much.
I am new to multi-thread coding.
Your explanation inspires me, really.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic