SlideShare une entreprise Scribd logo
1  sur  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”

Contenu connexe

En vedette (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
 

Similaire à The account problem in Java and Clojure

Rajeev oops 2nd march
Rajeev oops 2nd marchRajeev oops 2nd march
Rajeev oops 2nd march
Rajeev Sharan
 
Simple design/programming nuggets
Simple design/programming nuggetsSimple design/programming nuggets
Simple design/programming nuggets
Vivek Singh
 
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
ICSM 2010
 
Flow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time DebuggingFlow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time Debugging
lienhard
 
Tmpj3 01 201181102muhammad_tohir
Tmpj3 01 201181102muhammad_tohirTmpj3 01 201181102muhammad_tohir
Tmpj3 01 201181102muhammad_tohir
pencari buku
 
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
rajeshjangid1865
 
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
akshay1213
 
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
rajeshjain2109
 
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
ankitcom
 
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
anujmkt
 

Similaire à 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
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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
 
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...
 
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...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

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”

Notes de l'éditeur

  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.