SlideShare a Scribd company logo
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”

More Related Content

Viewers also liked (11)

KEY
Into Clojure
Alf Kristian Støyle
 
KEY
Clojure - JVM språket som er "multi-core ready"
Alf Kristian Støyle
 
PPT
Likwidacja linii tramwaju szybkiego w Zielonej Górze
Instytut Ekonomiki Miast i Regionów
 
DOCX
Assignment 7
IIUM
 
PDF
Paralell collections in Scala
Alf Kristian Støyle
 
PDF
Chapter 04 inheritance
Nurhanna Aziz
 
PDF
Bank account in java
Programming Homework Help
 
DOCX
Logi
Yasser Lotfy
 
PPT
Java: Class Design Examples
Tareq Hasan
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PDF
Object Oriented Programming with Real World Examples
OXUS 20
 
Into Clojure
Alf Kristian Støyle
 
Clojure - JVM språket som er "multi-core ready"
Alf Kristian Støyle
 
Likwidacja linii tramwaju szybkiego w Zielonej Górze
Instytut Ekonomiki Miast i Regionów
 
Assignment 7
IIUM
 
Paralell collections in Scala
Alf Kristian Støyle
 
Chapter 04 inheritance
Nurhanna Aziz
 
Bank account in java
Programming Homework Help
 
Java: Class Design Examples
Tareq Hasan
 
Classes, objects in JAVA
Abhilash Nair
 
Object Oriented Programming with Real World Examples
OXUS 20
 

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

PDF
Event-driven systems without pulling your hair out
Andrzej Ludwikowski
 
PDF
Droid on Chain - Berry Ventura Lev, Kik
DroidConTLV
 
PDF
Rajeev oops 2nd march
Rajeev Sharan
 
PPTX
Actor Model
Pieter Joost van de Sande
 
PDF
Spring Transaction
Jannarong Wadthong
 
PDF
Improving application design with a rich domain model (springone 2007)
Chris Richardson
 
PDF
Inheritance
FALLEE31188
 
ODP
Simple design/programming nuggets
Vivek Singh
 
PDF
Atomically { Delete Your Actors }
John De Goes
 
PDF
Automatically Repairing Test Cases for Evolving Method Declarations
ICSM 2010
 
PDF
Flow-Centric, Back-In-Time Debugging
lienhard
 
PDF
"An introduction to object-oriented programming for those who have never done...
Fwdays
 
DOCX
Tmpj3 01 201181102muhammad_tohir
pencari buku
 
PPTX
Dependency injection - the right way
Thibaud Desodt
 
PDF
I need help creating a basic and simple Java program. Here is the ex.pdf
rajeshjangid1865
 
PDF
Gerenciamento de estado no Angular com NgRx
Loiane Groner
 
PDF
The java class Account that simultes the Account class.pdf
akshay1213
 
PDF
Banks offer various types of accounts, such as savings, checking, cer.pdf
rajeshjain2109
 
PDF
public class InsufficientFundsException extends Exception{Insuffic.pdf
ankitcom
 
PDF
Account.h Definition of Account class. #ifndef ACCOUNT_H #d.pdf
anujmkt
 
Event-driven systems without pulling your hair out
Andrzej Ludwikowski
 
Droid on Chain - Berry Ventura Lev, Kik
DroidConTLV
 
Rajeev oops 2nd march
Rajeev Sharan
 
Spring Transaction
Jannarong Wadthong
 
Improving application design with a rich domain model (springone 2007)
Chris Richardson
 
Inheritance
FALLEE31188
 
Simple design/programming nuggets
Vivek Singh
 
Atomically { Delete Your Actors }
John De Goes
 
Automatically Repairing Test Cases for Evolving Method Declarations
ICSM 2010
 
Flow-Centric, Back-In-Time Debugging
lienhard
 
"An introduction to object-oriented programming for those who have never done...
Fwdays
 
Tmpj3 01 201181102muhammad_tohir
pencari buku
 
Dependency injection - the right way
Thibaud Desodt
 
I need help creating a basic and simple Java program. Here is the ex.pdf
rajeshjangid1865
 
Gerenciamento de estado no Angular com NgRx
Loiane Groner
 
The java class Account that simultes the Account class.pdf
akshay1213
 
Banks offer various types of accounts, such as savings, checking, cer.pdf
rajeshjain2109
 
public class InsufficientFundsException extends Exception{Insuffic.pdf
ankitcom
 
Account.h Definition of Account class. #ifndef ACCOUNT_H #d.pdf
anujmkt
 
Ad

Recently uploaded (20)

PPTX
Extensions Framework (XaaS) - Enabling Orchestrate Anything
ShapeBlue
 
PDF
How a Code Plagiarism Checker Protects Originality in Programming
Code Quiry
 
PPTX
python advanced data structure dictionary with examples python advanced data ...
sprasanna11
 
PDF
Novus Safe Lite- What is Novus Safe Lite.pdf
Novus Hi-Tech
 
PDF
Rethinking Security Operations - Modern SOC.pdf
Haris Chughtai
 
PDF
CloudStack GPU Integration - Rohit Yadav
ShapeBlue
 
PDF
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
PPTX
The Yotta x CloudStack Advantage: Scalable, India-First Cloud
ShapeBlue
 
PDF
CIFDAQ'S Token Spotlight for 16th July 2025 - ALGORAND
CIFDAQ
 
PDF
The Past, Present & Future of Kenya's Digital Transformation
Moses Kemibaro
 
PDF
Upskill to Agentic Automation 2025 - Kickoff Meeting
DianaGray10
 
PPTX
AVL ( audio, visuals or led ), technology.
Rajeshwri Panchal
 
PDF
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
PPTX
Lecture 5 - Agentic AI and model context protocol.pptx
Dr. LAM Yat-fai (林日辉)
 
PDF
State-Dependent Conformal Perception Bounds for Neuro-Symbolic Verification
Ivan Ruchkin
 
PDF
Apache CloudStack 201: Let's Design & Build an IaaS Cloud
ShapeBlue
 
PPTX
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
PPTX
Machine Learning Benefits Across Industries
SynapseIndia
 
PDF
Novus-Safe Pro: Brochure-What is Novus Safe Pro?.pdf
Novus Hi-Tech
 
PDF
UiPath on Tour London Community Booth Deck
UiPathCommunity
 
Extensions Framework (XaaS) - Enabling Orchestrate Anything
ShapeBlue
 
How a Code Plagiarism Checker Protects Originality in Programming
Code Quiry
 
python advanced data structure dictionary with examples python advanced data ...
sprasanna11
 
Novus Safe Lite- What is Novus Safe Lite.pdf
Novus Hi-Tech
 
Rethinking Security Operations - Modern SOC.pdf
Haris Chughtai
 
CloudStack GPU Integration - Rohit Yadav
ShapeBlue
 
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
The Yotta x CloudStack Advantage: Scalable, India-First Cloud
ShapeBlue
 
CIFDAQ'S Token Spotlight for 16th July 2025 - ALGORAND
CIFDAQ
 
The Past, Present & Future of Kenya's Digital Transformation
Moses Kemibaro
 
Upskill to Agentic Automation 2025 - Kickoff Meeting
DianaGray10
 
AVL ( audio, visuals or led ), technology.
Rajeshwri Panchal
 
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
Lecture 5 - Agentic AI and model context protocol.pptx
Dr. LAM Yat-fai (林日辉)
 
State-Dependent Conformal Perception Bounds for Neuro-Symbolic Verification
Ivan Ruchkin
 
Apache CloudStack 201: Let's Design & Build an IaaS Cloud
ShapeBlue
 
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
Machine Learning Benefits Across Industries
SynapseIndia
 
Novus-Safe Pro: Brochure-What is Novus Safe Pro?.pdf
Novus Hi-Tech
 
UiPath on Tour London Community Booth Deck
UiPathCommunity
 
Ad

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”

Editor's Notes

  • #8: * One mutable field -&gt; real app * Reason about -&gt; honestly * Difficult test * Inherently difficult with locks
  • #9: everything is immutable. -&gt; List
  • #10: everything is immutable. -&gt; List
  • #11: everything is immutable. -&gt; List
  • #12: Claim a lot simpler than the Java version * easier to reason * easier to test -&gt; no deadlocking
  • #13: Claim a lot simpler than the Java version * easier to reason * easier to test -&gt; no deadlocking
  • #14: Claim a lot simpler than the Java version * easier to reason * easier to test -&gt; no deadlocking
  • #15: Claim a lot simpler than the Java version * easier to reason * easier to test -&gt; no deadlocking
  • #16: Claim a lot simpler than the Java version * easier to reason * easier to test -&gt; no deadlocking
  • #17: Claim a lot simpler than the Java version * easier to reason * easier to test -&gt; no deadlocking
  • #18: Good reason to look at Clojure.