1

I am attempting to update a value in my application, lets call it a Foo object. Foo is immutable as a java object but can be updated in the database via a Hibernate entity. I am accessing Foo objects by calling a loading cache overlay (Guava Cache as the implementation) that loads the value from the database when it isn't present. In addition, there will be few writes but many reads to Foo objects, though concurrent writes are possible.

What is the best way to update a Foo object? Locking the cache on update? Some other structural design?

Note, there is definitely information on this subject out in the vast Internets, but I read so much of it trying to figure this out that I confused myself. I am currently leaning towards a ReentrantLock on the update method of the cache implementation class, but it seems like there should be a better way.

oberger
  • 1,217
  • 2
  • 16
  • 31
  • Does the various parts of the application need to know that the "immutable" object has changed? – Thorbjørn Ravn Andersen Dec 18 '14 at 19:36
  • @ThorbjørnRavnAndersen, no, I don't think so, unless another "writer" needs to know about it so that I don't have a race condition when updating an object. – oberger Dec 18 '14 at 19:51
  • 1
    The usual solution is to have events fired when objects are updated, see Swing for an example of a large code base to do so. You can use locks and synchronization to avoid overlapping updates. – Thorbjørn Ravn Andersen Dec 18 '14 at 22:39

1 Answers1

0

I am not totally sure whether I get your question right. However the problem seems identical/similar to the one I answered here: Guava Cache, how to block access while doing removal

If not, please add more detail.

Community
  • 1
  • 1
cruftex
  • 5,545
  • 2
  • 20
  • 36
  • Could you elaborate a little more on how you "touch" the data to start the transaction (solution #1 from the link), but still maintain abstraction from the data layer? I guess I don't understand how you make what appears to be two round trips from the business layer to the data layer all take place under one transaction. – oberger Dec 19 '14 at 17:10
  • This indeed seems to be a design problem by me, but locking should resolve and race issues... I am going to try your third solution, but with a special channel only for updates, as any reads from the DB will occur either before or after Hibernate releases the automatic lock from the update, which I'm okay with. Also, I am using the Striped from Guava for the lock-striping, though I do like your quick and dirty solution. – oberger Dec 19 '14 at 17:12