Implements save (or commit) and rollback methods to a Map

萝らか妹 提交于 2021-02-11 13:05:01

问题


I'm searching for a fast and convenient way to add save() and rollback() to a standard Map. Let's say i have an object 'table' of class Table which in turn has a private Map called 'rows'. What I'm trying to achieve is a fast and without memory waste method for Row to do something like:

row = new Row();
table.addRow(row).setValue("col1", "foo").setValue("col2", "bar").save();
row.setValue("col2", "beer");
System.out.println(table.getRows()); // 1. col1=foo, col2=bar

row.save();
System.out.println(table.getRows()); // 1. col1=foo, col2=beer

Actually, my design is quite trivial: when addRow() is called, i put() the row inside the map; no buffer, no temp elements; i simply pass the entire Row instance to rows collection. But I need a fast method and (if possible) avoiding the duplication of rows.

any idea?


回答1:


This sounds too much like "I want to have the new and old values in memory, but I do not want to have the new and old values in memory".

Options:

a) A map of all the added elements, when save do putAll.

b) Your map, instead of <ClassKey, ClassValue>, holds <ClassKey, ClassValue2>. Value2 holds two items of ClassValue, the new and old instance. At save, you pass the new one (if any) to the old one. It will be useful only if you are changing most of the entries in each "transaction".

Not mentioned is the issue of deleting elements, which will bring you yet more joy. With option 2 you can set a boolean at Value2, with option a you will need more workarounds.




回答2:


What I'm trying to achieve is a fast and without memory waste method for Row to do something like:

You will waste memory, as you need to keep a "rollback" around somewhere in case it fails along the way. This is how databases handle these types of things.

Now to get the feature you want, you will need to implement your own custom transaction logic, this will allow you to correctly rollback / persist changes to your map. Now within this transaction you will need to keep track of everything that occurred during the transaction. This is because you will be doing temporary writes to your original map, while the transaction processes, subsequently you will need to have the ability to recover from a failed persist/update.

To avoid duplication of rows, the HashMap will already save you from that problem. Assuming you correctly implement a hash function that reports correctly when two objects generate the same code and are therefore "potentially", not definitely, equal in terms of hashing.



来源:https://stackoverflow.com/questions/13922809/implements-save-or-commit-and-rollback-methods-to-a-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!