SlideShare una empresa de Scribd logo
1 de 18
The account problem in Java and
            Clojure




          Alf Kristian Støyle
public class Account {

     private long balance;
      private final int accountNo;


    public void debit(long debitAmount) {

    
     this.balance -= debitAmount;

    }


    public void credit(long creditAmount) {

    
     this.balance += creditAmount;

    }


    public long getBalance() {

    
     return this.balance;

    }


    public void getAccountNo() {

    
     return this.accountNo;

    }
}
public class Account {

     private volatile long balance;
      private final int accountNo;


    public synchronized void debit(long debitAmount) {

    
     this.balance -= debitAmount;

    }


    public synchronized void credit(long creditAmount) {

    
     this.balance += creditAmount;

    }


    public synchronized long getBalance() {

    
     return this.balance;

    }


    public void getAccountNo() {

    
     return this.accountNo;

    }
}
public void transfer(Account fromAccount, Account toAccount,
                     long amount) throws Exception {

    if (fromAccount.getBalance() < amount) {
        throw new Exception("Not enough money!");
    }
    fromAccount.debit(amount);
    toAccount.credit(amount);
}
public void transfer(Account fromAccount, Account toAccount,
                     long amount) throws Exception {

    synchronized (fromAccount) {
        synchronized (toAccount) {

           if (fromAccount.getBalance() < amount) {
               throw new Exception("Not enough money!");
  
         }
  
         fromAccount.debit(amount);

           toAccount.credit(amount);

       }
    }
}
public void transfer(Account fromAccount, Account toAccount,
                     long amount) throws Exception {

    Object mutex1 = toAccount;
    Object mutex2 = fromAccount;
    if (fromAccount.getAccountNo() > toAccount.getAccountNo()) {
        mutex1 = fromAccount;
        mutex2 = toAccount;
    }
    synchronized (mutex1) {
        synchronized (mutex2) {
            if (fromAccount.getBalance() < amount) {
                throw new Exception("Not enough money!");
            }
            fromAccount.debit(amount);
            toAccount.credit(amount);
        }
    }
}
public class Account {
             private volatile long balance;
             private final int accountNo;

             public synchronized void debit(long debitAmount) {
                 this.balance -= debitAmount;
             }
         
             public synchronized void credit(long creditAmount) {
                 this.balance += creditAmount;
             }

             public synchronized long getBalance() {
                 return this.balance;
             }

             public void getAccountNo() {
                 return this.accountNo;
             }
         }
public void transfer(Account fromAccount, Account toAccount,
                     long amount) throws Exception {

    Object mutex1 = toAccount;
    Object mutex2 = fromAccount;
    if (fromAccount.getAccountNo() > toAccount.getAccountNo()) {
        mutex1 = fromAccount;
        mutex2 = toAccount;
    }
    synchronized (mutex1) {
        synchronized (mutex2) {
            if (fromAccount.getBalance() < amount) {
                throw new Exception("Not enough money!");
            }
            fromAccount.debit(amount);
            toAccount.credit(amount);
        }
    }
}
Clojure
Clojure
• Pure functional
Clojure
• Pure functional
• Managed references
 • Ref
 • ...
Clojure
• Pure functional
• Managed references
 • Ref
 • ...
• Software transactional memory
(defn transfer [from-account to-account amount]
  (dosync
    (if (> amount @from-account)
      (throw (Exception. "Not enough money!")))
    (alter from-account - amount)
    (alter to-account + amount)))
(defn transfer [from-account to-account amount]
  (dosync
    (if (> amount @from-account)
      (throw (Exception. "Not enough money!")))
    (alter from-account - amount)
    (alter to-account + amount)))




   OMG it’s a Lisp!
(defn transfer [from-account to-account amount]
  (dosync
    (if (> amount @from-account)
      (throw (Exception. "Not enough money!")))
    (alter from-account - amount)
    (alter to-account + amount)))
(defn transfer [from-account to-account amount]
  (dosync
    (if (> amount @from-account)
      (throw (Exception. "Not enough money!")))
    (alter from-account - amount)
    (alter to-account + amount)))


(def account-a (ref 1000))
(def account-b (ref 800))
(defn transfer [from-account to-account amount]
  (dosync
    (if (> amount @from-account)
      (throw (Exception. "Not enough money!")))
    (alter from-account - amount)
    (alter to-account + amount)))


(def account-a (ref 1000))
(def account-b (ref 800))


(transfer account-a account-b 300)

@account-a
=> 700
(defn transfer [from-account to-account amount]
  (dosync
    (if (> amount @from-account)
      (throw (Exception. "Not enough money!")))
    (alter from-account - amount)
    (alter to-account + amount)))


(def account-a (ref 1000))
(def account-b (ref 800))


(alter account-a - 100)
=> java.lang.IllegalStateException:
   No transaction running
The pragmatic programmers




“Learn at least one new language every year”

Más contenido relacionado

Destacado

Clojure - JVM språket som er "multi-core ready"
Clojure - JVM språket som er "multi-core ready"Clojure - JVM språket som er "multi-core ready"
Clojure - JVM språket som er "multi-core ready"Alf Kristian Støyle
 
Assignment 7
Assignment 7Assignment 7
Assignment 7IIUM
 
Chapter 04 inheritance
Chapter 04 inheritanceChapter 04 inheritance
Chapter 04 inheritanceNurhanna Aziz
 
Java: Class Design Examples
Java: Class Design ExamplesJava: Class Design Examples
Java: Class Design ExamplesTareq Hasan
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesOXUS 20
 

Destacado (11)

Into Clojure
Into ClojureInto Clojure
Into Clojure
 
Clojure - JVM språket som er "multi-core ready"
Clojure - JVM språket som er "multi-core ready"Clojure - JVM språket som er "multi-core ready"
Clojure - JVM språket som er "multi-core ready"
 
Likwidacja linii tramwaju szybkiego w Zielonej Górze
Likwidacja linii tramwaju szybkiego w Zielonej GórzeLikwidacja linii tramwaju szybkiego w Zielonej Górze
Likwidacja linii tramwaju szybkiego w Zielonej Górze
 
Assignment 7
Assignment 7Assignment 7
Assignment 7
 
Paralell collections in Scala
Paralell collections in ScalaParalell collections in Scala
Paralell collections in Scala
 
Chapter 04 inheritance
Chapter 04 inheritanceChapter 04 inheritance
Chapter 04 inheritance
 
Bank account in java
Bank account in javaBank account in java
Bank account in java
 
Logi
LogiLogi
Logi
 
Java: Class Design Examples
Java: Class Design ExamplesJava: Class Design Examples
Java: Class Design Examples
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World Examples
 

Similar a The account problem in Java and Clojure

Droid on Chain - Berry Ventura Lev, Kik
Droid on Chain - Berry Ventura Lev, KikDroid on Chain - Berry Ventura Lev, Kik
Droid on Chain - Berry Ventura Lev, KikDroidConTLV
 
Rajeev oops 2nd march
Rajeev oops 2nd marchRajeev oops 2nd march
Rajeev oops 2nd marchRajeev Sharan
 
Improving application design with a rich domain model (springone 2007)
Improving application design with a rich domain model (springone 2007)Improving application design with a rich domain model (springone 2007)
Improving application design with a rich domain model (springone 2007)Chris Richardson
 
Simple design/programming nuggets
Simple design/programming nuggetsSimple design/programming nuggets
Simple design/programming nuggetsVivek Singh
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }John De Goes
 
Automatically Repairing Test Cases for Evolving Method Declarations
Automatically Repairing Test Cases for Evolving Method DeclarationsAutomatically Repairing Test Cases for Evolving Method Declarations
Automatically Repairing Test Cases for Evolving Method DeclarationsICSM 2010
 
Flow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time DebuggingFlow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time Debugginglienhard
 
"An introduction to object-oriented programming for those who have never done...
"An introduction to object-oriented programming for those who have never done..."An introduction to object-oriented programming for those who have never done...
"An introduction to object-oriented programming for those who have never done...Fwdays
 
Tmpj3 01 201181102muhammad_tohir
Tmpj3 01 201181102muhammad_tohirTmpj3 01 201181102muhammad_tohir
Tmpj3 01 201181102muhammad_tohirpencari buku
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right wayThibaud Desodt
 
I need help creating a basic and simple Java program. Here is the ex.pdf
I need help creating a basic and simple Java program. Here is the ex.pdfI need help creating a basic and simple Java program. Here is the ex.pdf
I need help creating a basic and simple Java program. Here is the ex.pdfrajeshjangid1865
 
Gerenciamento de estado no Angular com NgRx
Gerenciamento de estado no Angular com NgRxGerenciamento de estado no Angular com NgRx
Gerenciamento de estado no Angular com NgRxLoiane Groner
 
The java class Account that simultes the Account class.pdf
   The java class Account that simultes  the Account class.pdf   The java class Account that simultes  the Account class.pdf
The java class Account that simultes the Account class.pdfakshay1213
 
Banks offer various types of accounts, such as savings, checking, cer.pdf
Banks offer various types of accounts, such as savings, checking, cer.pdfBanks offer various types of accounts, such as savings, checking, cer.pdf
Banks offer various types of accounts, such as savings, checking, cer.pdfrajeshjain2109
 
public class InsufficientFundsException extends Exception{Insuffic.pdf
public class InsufficientFundsException extends Exception{Insuffic.pdfpublic class InsufficientFundsException extends Exception{Insuffic.pdf
public class InsufficientFundsException extends Exception{Insuffic.pdfankitcom
 
Account.h Definition of Account class. #ifndef ACCOUNT_H #d.pdf
Account.h  Definition of Account class. #ifndef ACCOUNT_H #d.pdfAccount.h  Definition of Account class. #ifndef ACCOUNT_H #d.pdf
Account.h Definition of Account class. #ifndef ACCOUNT_H #d.pdfanujmkt
 
Principais vulnerabilidades em Smart Contracts e como evitá-las
Principais vulnerabilidades em Smart Contracts e como evitá-lasPrincipais vulnerabilidades em Smart Contracts e como evitá-las
Principais vulnerabilidades em Smart Contracts e como evitá-lasJúlio Campos
 

Similar a The account problem in Java and Clojure (20)

Droid on Chain - Berry Ventura Lev, Kik
Droid on Chain - Berry Ventura Lev, KikDroid on Chain - Berry Ventura Lev, Kik
Droid on Chain - Berry Ventura Lev, Kik
 
Rajeev oops 2nd march
Rajeev oops 2nd marchRajeev oops 2nd march
Rajeev oops 2nd march
 
Actor Model
Actor ModelActor Model
Actor Model
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
 
Improving application design with a rich domain model (springone 2007)
Improving application design with a rich domain model (springone 2007)Improving application design with a rich domain model (springone 2007)
Improving application design with a rich domain model (springone 2007)
 
Inheritance
InheritanceInheritance
Inheritance
 
Simple design/programming nuggets
Simple design/programming nuggetsSimple design/programming nuggets
Simple design/programming nuggets
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 
Automatically Repairing Test Cases for Evolving Method Declarations
Automatically Repairing Test Cases for Evolving Method DeclarationsAutomatically Repairing Test Cases for Evolving Method Declarations
Automatically Repairing Test Cases for Evolving Method Declarations
 
Flow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time DebuggingFlow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time Debugging
 
"An introduction to object-oriented programming for those who have never done...
"An introduction to object-oriented programming for those who have never done..."An introduction to object-oriented programming for those who have never done...
"An introduction to object-oriented programming for those who have never done...
 
Tmpj3 01 201181102muhammad_tohir
Tmpj3 01 201181102muhammad_tohirTmpj3 01 201181102muhammad_tohir
Tmpj3 01 201181102muhammad_tohir
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
I need help creating a basic and simple Java program. Here is the ex.pdf
I need help creating a basic and simple Java program. Here is the ex.pdfI need help creating a basic and simple Java program. Here is the ex.pdf
I need help creating a basic and simple Java program. Here is the ex.pdf
 
Gerenciamento de estado no Angular com NgRx
Gerenciamento de estado no Angular com NgRxGerenciamento de estado no Angular com NgRx
Gerenciamento de estado no Angular com NgRx
 
The java class Account that simultes the Account class.pdf
   The java class Account that simultes  the Account class.pdf   The java class Account that simultes  the Account class.pdf
The java class Account that simultes the Account class.pdf
 
Banks offer various types of accounts, such as savings, checking, cer.pdf
Banks offer various types of accounts, such as savings, checking, cer.pdfBanks offer various types of accounts, such as savings, checking, cer.pdf
Banks offer various types of accounts, such as savings, checking, cer.pdf
 
public class InsufficientFundsException extends Exception{Insuffic.pdf
public class InsufficientFundsException extends Exception{Insuffic.pdfpublic class InsufficientFundsException extends Exception{Insuffic.pdf
public class InsufficientFundsException extends Exception{Insuffic.pdf
 
Account.h Definition of Account class. #ifndef ACCOUNT_H #d.pdf
Account.h  Definition of Account class. #ifndef ACCOUNT_H #d.pdfAccount.h  Definition of Account class. #ifndef ACCOUNT_H #d.pdf
Account.h Definition of Account class. #ifndef ACCOUNT_H #d.pdf
 
Principais vulnerabilidades em Smart Contracts e como evitá-las
Principais vulnerabilidades em Smart Contracts e como evitá-lasPrincipais vulnerabilidades em Smart Contracts e como evitá-las
Principais vulnerabilidades em Smart Contracts e como evitá-las
 

Último

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 

Último (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

The account problem in Java and Clojure

  • 1. The account problem in Java and Clojure Alf Kristian Støyle
  • 2. public class Account { private long balance; private final int accountNo; public void debit(long debitAmount) { this.balance -= debitAmount; } public void credit(long creditAmount) { this.balance += creditAmount; } public long getBalance() { return this.balance; } public void getAccountNo() { return this.accountNo; } }
  • 3. public class Account { private volatile long balance; private final int accountNo; public synchronized void debit(long debitAmount) { this.balance -= debitAmount; } public synchronized void credit(long creditAmount) { this.balance += creditAmount; } public synchronized long getBalance() { return this.balance; } public void getAccountNo() { return this.accountNo; } }
  • 4. public void transfer(Account fromAccount, Account toAccount, long amount) throws Exception { if (fromAccount.getBalance() < amount) { throw new Exception("Not enough money!"); } fromAccount.debit(amount); toAccount.credit(amount); }
  • 5. public void transfer(Account fromAccount, Account toAccount, long amount) throws Exception { synchronized (fromAccount) { synchronized (toAccount) { if (fromAccount.getBalance() < amount) { throw new Exception("Not enough money!"); } fromAccount.debit(amount); toAccount.credit(amount); } } }
  • 6. public void transfer(Account fromAccount, Account toAccount, long amount) throws Exception { Object mutex1 = toAccount; Object mutex2 = fromAccount; if (fromAccount.getAccountNo() > toAccount.getAccountNo()) { mutex1 = fromAccount; mutex2 = toAccount; } synchronized (mutex1) { synchronized (mutex2) { if (fromAccount.getBalance() < amount) { throw new Exception("Not enough money!"); } fromAccount.debit(amount); toAccount.credit(amount); } } }
  • 7. public class Account { private volatile long balance; private final int accountNo; public synchronized void debit(long debitAmount) { this.balance -= debitAmount; } public synchronized void credit(long creditAmount) { this.balance += creditAmount; } public synchronized long getBalance() { return this.balance; } public void getAccountNo() { return this.accountNo; } } public void transfer(Account fromAccount, Account toAccount, long amount) throws Exception { Object mutex1 = toAccount; Object mutex2 = fromAccount; if (fromAccount.getAccountNo() > toAccount.getAccountNo()) { mutex1 = fromAccount; mutex2 = toAccount; } synchronized (mutex1) { synchronized (mutex2) { if (fromAccount.getBalance() < amount) { throw new Exception("Not enough money!"); } fromAccount.debit(amount); toAccount.credit(amount); } } }
  • 10. Clojure • Pure functional • Managed references • Ref • ...
  • 11. Clojure • Pure functional • Managed references • Ref • ... • Software transactional memory
  • 12. (defn transfer [from-account to-account amount] (dosync (if (> amount @from-account) (throw (Exception. "Not enough money!"))) (alter from-account - amount) (alter to-account + amount)))
  • 13. (defn transfer [from-account to-account amount] (dosync (if (> amount @from-account) (throw (Exception. "Not enough money!"))) (alter from-account - amount) (alter to-account + amount))) OMG it’s a Lisp!
  • 14. (defn transfer [from-account to-account amount] (dosync (if (> amount @from-account) (throw (Exception. "Not enough money!"))) (alter from-account - amount) (alter to-account + amount)))
  • 15. (defn transfer [from-account to-account amount] (dosync (if (> amount @from-account) (throw (Exception. "Not enough money!"))) (alter from-account - amount) (alter to-account + amount))) (def account-a (ref 1000)) (def account-b (ref 800))
  • 16. (defn transfer [from-account to-account amount] (dosync (if (> amount @from-account) (throw (Exception. "Not enough money!"))) (alter from-account - amount) (alter to-account + amount))) (def account-a (ref 1000)) (def account-b (ref 800)) (transfer account-a account-b 300) @account-a => 700
  • 17. (defn transfer [from-account to-account amount] (dosync (if (> amount @from-account) (throw (Exception. "Not enough money!"))) (alter from-account - amount) (alter to-account + amount))) (def account-a (ref 1000)) (def account-b (ref 800)) (alter account-a - 100) => java.lang.IllegalStateException: No transaction running
  • 18. The pragmatic programmers “Learn at least one new language every year”

Notas del editor

  1. * One mutable field -&gt; real app * Reason about -&gt; honestly * Difficult test * Inherently difficult with locks
  2. everything is immutable. -&gt; List
  3. everything is immutable. -&gt; List
  4. everything is immutable. -&gt; List
  5. Claim a lot simpler than the Java version * easier to reason * easier to test -&gt; no deadlocking
  6. Claim a lot simpler than the Java version * easier to reason * easier to test -&gt; no deadlocking
  7. Claim a lot simpler than the Java version * easier to reason * easier to test -&gt; no deadlocking
  8. Claim a lot simpler than the Java version * easier to reason * easier to test -&gt; no deadlocking
  9. Claim a lot simpler than the Java version * easier to reason * easier to test -&gt; no deadlocking
  10. Claim a lot simpler than the Java version * easier to reason * easier to test -&gt; no deadlocking
  11. Good reason to look at Clojure.