What is Persistence?

Persistence is the ability to restore an object to its previous state after shutting off the system or exiting the program.

Normally, any objects created by a C++ program cease to exist when the program exits. Persistence is the ability to keep the object available after the program exits and to be able to access that object in other programs. Specifically, we want to preserve the object's state, so that we can recreate it later, either in another program or when we rerun the current program.

In Star Trek, Captain Kirk was forever stepping into the transporter and twinkling his way to the planet surface. You can imagine that the transporter was storing his state so that he could be restored elsewhere. If his state were restored perfectly, neither he nor anyone else would doubt he was the same person.

Imagine, further, that instead of restoring him immediately, the computer wrote his state to hard disk (or titanium holographic memory, if you prefer). This would be a persistence mechanism, which would allow the computer to restore Kirk to his former vainglorious self at a later date.

A real-world example of this is the ever-popular ATM example, in which a bank account must be updated for a user's transaction. Assume the user deposits $500 into an account that had a previous balance of $1000. Now, the new state of the account must be preserved so that the next time the account is accessed (perhaps through the customer's home banking program), the balance is shown as $1500, not as the original $1000. Even if the ATM goes off line, the bank balance must be maintained. The bank accomplishes this by writing the balance to an account in a database.

Without persistence, the moment the bank's computers shut down, every record of every transaction would be wiped out. The next month you'd get your statement. "Greetings. Due to a power failure, we reset our memory. Your new balance is $100."

Even if the computer were never turned off and never crashed, without persistence every item of information would have to be maintained in RAM. There is only so much RAM in most computers as cost is a major factor. To buy an additional Gigabyte of RAM costs about a thousand dollars, the cost of disk storage is one tenth that or less. In short, modern database systems would be impossible without some form of persistence.

© 1998 by Wrox Press. All rights reserved.