Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Large Data Structure in Clojure STM for Banking Transactions LOOP

Tags:

clojure

stm

I am new to Functional Programming and Clojure, so I am not really sure about what to do for a project at University. The project should show the advantage of Clojure STM for banking transactions (Transfer of money from account A to account B). So I plan to proceed this way:

  1. define initial data, like a matrix of Refs or something better
  2. generate random operations to execute: [ random-account-source-id(0, N_MAX) , random-account-destination-id(0, N_MAX), random-money (0, 1000) ]
  3. insert the transaction into the data structure
  4. Sync transfer of money from source-id to destination-id for all the insertions in 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, then, maybe:

(defn do-all[]
  (dosync
    (when (pos? N)
      (transfer (get matrix [pos 1], get matrix [pos 2], get matrix [pos 3])))))
like image 949
nuvio Avatar asked Dec 28 '22 04:12

nuvio


1 Answers

Represent the account with a Ref i.e a Ref for each account and perform the money transfer operation in a dosync operation. Also make sure you dont do any side-effect operation (other than on those Refs) in the dosync operation as it may be retried in case of a conflict while updating refs.

Update: In case you will have the number of accounts fixed then you could use ref of vectors where each ref in the vector is an account and each account is identified by the index in the vector.

Ex:

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

In case you have to dynamically add new accounts and identify them by name then you can use hash map where key is the account id (unique value) and value is the Ref for account balance. You will need to wrap this map in a Ref in case you want to do concurrent operations for adding/removing accounts from multiple threads.

like image 140
Ankur Avatar answered May 16 '23 09:05

Ankur