Big data structure in Clojure STM for banking transactions LOOP

I am new to functional programming and Clojure, so I'm not quite sure what to do for a project at the university. The project should demonstrate the advantage of Clojure STM for banking operations (transferring money from account A to account B). Therefore, I plan to continue this path:

  • Define source data, for example, a Ref matrix or better.
  • generate random operations to perform: [ random-account-source-id(0, N_MAX) , random-account-destination-id(0, N_MAX), random-money (0, 1000) ]
  • insert transaction into data structure
  • Synchronization of money transfer from the source identifier to the destination identifier for all insertions into the matrix, such as:
     for i=0; i lt N; i++; synchronize: transfer (matrix[i].source,matrix[i].dest,matrix[i].money) 

I'm not sure about this, maybe:

 (defn do-all[] (dosync (when (pos? N) (transfer (get matrix [pos 1], get matrix [pos 2], get matrix [pos 3]))))) 
+4
source share
2 answers

Introduce an account with Ref ie Ref for each account and complete the money transfer operation in dosync operations. Also, make sure that you do not perform any side effect operation (other than those specified in Refs) in the dosync operation, since it can be repeated in case of conflict when updating links.

Update: If you have the number of corrected accounts, you can use ref vectors where each ref in the vector is an account and each account is identified by an index in the vector.

Example:

 (def total-accounts 100) (def accounts (vec (map (fn [_] (ref 100)) (range total-accounts)))) 

If you need to dynamically add new accounts and identify them by name, you can use a hash map where the key is the account identifier (unique value) and the value is Ref for the account balance. You will need to wrap this card in Ref if you want to perform parallel operations to add / remove accounts from multiple threads.

+6
source

You might be interested in this Clojure STM example used for banking transactions , which I posted in response to another question.

+4
source

Source: https://habr.com/ru/post/1399547/


All Articles