2

I use java serialization to save my java objects into files. I would like to implement a new system where I only save the object if any changes have been made to it. Is there any java built in option to detect if an object changed during the execution of the program?

Or the only way to detect this is by using a flag that will change if any of the setters of the object is called?

Thanks

Daniel Oliveira
  • 1,280
  • 14
  • 36
  • Correct, there is no built-in "dirty" flag for objects. If you know your accesses are always through bean patterns, then you can accomplish maintaining that flag there. – BadZen Nov 16 '16 at 19:47
  • 1
    Looks like you're trying to do [this](http://stackoverflow.com/questions/2644847/how-to-generate-a-checksum-for-an-java-object) – aldito2 Nov 16 '16 at 19:47
  • Another option is to use something like AspectJ to instrument bytecode when you load it and set a "dirty" flag whenever a field is changed. This will work even if the access is not always from a bean pattern method. – BadZen Nov 16 '16 at 19:48
  • @aldito2 - Hashcodes / checksums do not solve this problem. If the checksum matches, you don't know if the object has been changed or not - as the mutation could map the object into a state which hash-collides with the original state. You've got to check the whole object against the whole saved object, after that. – BadZen Nov 16 '16 at 19:49
  • You have phrased your two questions as 1 (paradoxical) question: (a) No, there is nothing built-in (b) The method that you describe is not the only way to detect if the object has changed – ControlAltDel Nov 16 '16 at 19:50
  • 1
    @BadZen : AspectJ does not involve bytecode manipulation at runtime, it uses InvocationHandler – rkosegi Nov 16 '16 at 19:51
  • Huh, I thought it could do either/or. What is "Load Time Weaving", then? (I'm pretty sure that's what it is... been awhile but I'm fairly certain I've done this) – BadZen Nov 16 '16 at 19:52
  • Yeah, take a look at: https://eclipse.org/aspectj/doc/released/devguide/ltw.html – BadZen Nov 16 '16 at 19:56
  • @BadZen though a checksum/hashcode is not full-proof it is a way of optimizing the comparison, first compare the checksums and if they are the same then do a full comparison to ensure you dont have a collision on the checksum – Danny Nov 16 '16 at 22:39
  • There is nothing optimal about serializing every object that doesn't change (because its hash matches) - that is exactly the cost OP is trying to avoid when he was motivated to ask this question. – BadZen Nov 16 '16 at 23:46

0 Answers0