Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top