Of course, this will not happen, but how best you can do is store a bank account without using the database only RAM in a multi-threaded environment, as I understand it, you can use AtomicInteger to store the amount, and an exact charge is guaranteed. But how can we ensure atomicity, for example, for one user to be written off and enrolled for the second one following the principle of consistency and sustainability. It would be desirable as in a DB was agreed.

void process(Account from, Account to, int sum) { AtomicInteger fromAtomicInteger = from.getAmount(); AtomicInteger toAtomicInteger = to.getAmount(); toAtomicInteger.addAndGet(sum); // что если выключится компьютер, допустим данные сохраняется после выключения fromAtomicInteger.addAndGet(-sum); } 
  • I do not understand the question. in the body of the question one, and in the code under the comment another. what exactly needs to be done? - Senior Pomidor
  • one
    You yourself understand what is impossible? - Roman C
  • one
    @RomanC Why is it impossible? How do you think the databases work? - Zergatul
  • @Zergatul It is impossible for the data to be saved in RAM after turning off the computer. - Stas Dorozhko
  • one
    @StasDorozhko The author describes the theoretical situation, everything he writes in the RAM will remain somewhere when it is turned off. If he starts to write to the file, you get your own database. - Zergatul

1 answer 1

... that if the computer turns off, let's say the data is saved after shutdown

To ensure the sustainability of “as in a DBMS”, you need to introduce the concept of a transaction into the program, store information about transactions in a permanent memory (keep a transaction log), implement the rollback / redo logic.

Solution: keep the lock in permanent memory. Next pseudocode:

 //создаем запись в журнале транзакций, //которая хранится в постоянном хранилище: //в базе данных, файловой системе и т.п. Transaction transaction = bank.createTransaction(from, to); ... //выполняем операции ... //отмечаем транзакцию как завершенную transaction.finish(); 

For simplicity, lowered exception handling.

If the computer turns off, the next time you start the application, it will read from the log entries about incomplete transactions and process them as necessary: ​​either roll back, finish it, or inform the user about data problems.

Also, for the correct operation of the above code, you will need to implement reliable transaction isolation . For example, after this line:

 toAtomicInteger.addAndGet(sum); 

another transaction may be executed, which will transfer money from the modified to account to the third account and successfully complete. If an error occurs after this, then the current transaction can no longer be rolled back painlessly. You can avoid this kind of errors by blocking accounts for the duration of the operation. Accordingly, such locks should also be stored in permanent memory.

DBMSs usually provide built-in transaction management mechanisms.

  • If this is a simple question, how consistency is achieved, at the technical level, when the two bases have to commit the data, one database sends a message that I am ready and waits for the second to respond, the second database responded, but where did the confidence that the first database received the answer from the second, the only thing that I I think this is some kind of timer to insert, but is performance lost? - Alexander Belov
  • @AlexanderBelov This is not a simple question. Providing performance along with isolation is the cornerstone of the entire database industry. - default locale
  • @AlexanderBelov Your new example (interaction between two remote databases) is very different from the question (recovery of a transaction when disconnected). Guaranteed message delivery: a separate topic that deserves separate consideration. You can read about the mechanism in TCP or ask a separate question. - default locale
  • one
    ok, I thought maybe there in two words you can say) - Alexander Belov
  • @AlexanderBelov Thank you for the mark! Glad to have something to help. - default locale