SlideShare a Scribd company logo
Java   TIPS














20070329 Java Programing Tips
String str1 = new String(“hoge”);
         String str2 = “hoge”;

   System.out.println(str1 == str2);
 System.out.println(str1.equals(str2));



False
True
== equals


                                      char[] value

      str1      str1                  int length

                                      boolean equals(Object obj)

                                      char[] value

      str2      str2                  int length

                                      boolean equals(Object obj)



 str1 == str2          str1                  str2
                       char[] value
 str1.equals(str2)
java.lang.String
public final class String implements java.io.Serializable, Comparable<String>, CharSequence{
  private final char value[];
  private final int count;
  public boolean equals(Object anObject) {
           if (this == anObject) {
              return true;
           }
           if (anObject instanceof String) {
              String anotherString = (String)anObject;
              int n = count;
              if (n == anotherString.count) {
                        char v1[] = value;
                        char v2[] = anotherString.value;
                        int i = offset;
                        int j = anotherString.offset;
                        while (n-- != 0) {
                           if (v1[i++] != v2[j++])
                                     return false;
                        }
                        return true;
              }
           }
           return false;
  }
equals




         True
                   False
                     Account equals


         Account           equals
public abstract class Account{
       private char[] custmorCode = new char[4];
       Account(char[] custmorCode){
               this.custmorCode = custmorCode;
       }
       public char[] getCustmorCode(){
               return this.custmorCode;
       }
       @Override public boolean equals(Object obj){
               //
      }
}
SavingAccount a1 = new SavingAccount(new char[]{‘0’,’1’,’2’,’3’});
    SavingAccount a2 = new SavingAccount(new char[]{‘9’,’1’,’2’,’3’});
TimeDepositAccount a3 = new TimeDepositAccount(new char[]{‘0’,’1’,’2’,’3’});
TimeDepositAccount a4 = new TimeDepositAccount(new char[]{‘9’,’1’,’2’,’3’});

                      System.out.println(a1.equals(a3));
                      System.out.println(a2.equals(a4));
                      System.out.println(a1.equals(a2));
                      System.out.println(a2.equals(a3));




True
True
False
False
getClass                          instanceof

                    boolean equals(Object obj)

       Object


     ClassCastException

  instanceof                             Class getClass()


                         → true                             → true
                                                  → false
                    → true
               → false
public abstract class Account{
         //
         @Override public boolean equals(Object obj){
                   if(obj instanceof Account){
                   //if(getClass() == obj.getClass()){
                              char[] compareCode = ((Account)obj).getCustmorCode();
                              if(custmorCode.length != compareCode.length){
                                         return false;
                              }
                              for(int i = 0; i<custmorCode.length; i++){
                                         if(custmorCode[i] != compareCode[i]){
                                                    return false;
                                         }
                              }
                              return true;
                   } else {
                              return false;
                   }
         }
}
20070329 Java Programing Tips
equals
java.lang.Object             String
           char[] value

equals                    Instanceof
         getClass          equals
20070329 Java Programing Tips
CASE:
Inspector




        Inspector
100ms
Inspector




        Inspector
100ms
Inspector         Account




   100ms
   100ms
   100ms
   100ms
   100ms          CPU
Inspector




            Inspector


Inspector
public class Account{
               private byte[] lock = new byte[0];
               private ArrayList<Inspector> targets = new ArrayList<Inspector>();

              public int get(int amount){
                          synchronized(lock){
                                       if(this.amount < amount){
                                                  return 0;
                                       }
                                       for(Inspector i : targets){
                                                  i.inspect();
                                       }
                                       this.amount = this.amount - amount;
                                       return amount;
                          }
              }
              public void addInspector(Inspector insp){
                          this.targets.add(insp);
              }

                                     addInspector
                              Inspector
CPU




      CPU
20070329 Java Programing Tips
String
   public class Main{
            public static void main(String[] args){
                     String className = "RefrectionTest";
                     RefrectionTest rt = null;
                     try{
                               rt = (RefrectionTest)Class
                                        .forName(className).newInstance();
                     } catch(Exception e) {
                     }
                     rt.dosth();
            }
   }


   public class RefrectionTest{
            public void dosth(){
                     System.out.println("Do Something");
            }
   }
String
public class Main{
          public static void main(String[] args){
                     String className = "RefrectionTest";
                     RefrectionTest rt = null;
                     try{
                               rt = (RefrectionTest)Class.forName(className).newInstance();
                     } catch(Exception e) {
                     }

                   String methodName = "dosth";
                   Method method = null;
                   try{
                            method = (Method)Class.forName(className)
                                              .getMethod(methodName,null);
                   } catch(Exception e) {
                   }
                   method.invoke(Class.forName(className).newInstance(),null);
         }
}
20070329 Java Programing Tips
import java.io.*;
public class Main{
             public static void main(String[] args){
                           Account a1 = new Account("hoge",5000);
                           a1.get(100);
                           try{
                                        ObjectOutputStream oos = new ObjectOutputStream(
                                                               new FileOutputStream("hoge.ser"));
                                        oos.writeObject(a1);
                                        oos.close();
                           } catch(Exception e) {}

                        System.out.println(a1);
                        Account ser = null;
                        try{
                                    ObjectInputStream ois = new ObjectInputStream(
                                                            new FileInputStream("hoge.ser"));
                                    ser = (Account)ois.readObject();
                                    ois.close();
                        } catch(Exception e) {}

                        ser.get(100);
                        System.out.println(ser);
           }
}

public class Account implements Serializable{      //        }
20070329 Java Programing Tips
20070329 Java Programing Tips
1               2
        100             100



                    0

                    0

              100

              100






   1           2
synchronized
               public class Account{
                            private int amount;
                            private byte[] lock = new byte[0];

                           Account(int amount){
                                         this.amount = amount;
                           }
                           public int get(int amount){
                                         synchronized(lock){
                                                     this.amount = this.amount - amount;
                                                     return amount;
                                         }
                           }
                           public void put(int amount){
                                         synchronized(lock){
                                                     this.amount = this.amount + amount;
                                         }
                           }
               }


   Synchonized:
synchronized

           1                   2
           100                 100



                           0

                     100

                           0

                     200



   2            1
volatile

                  public class Account{
                            private volatile int amount;

                           Account(int amount){
                                    this.amount = amount;
                           }

                           public int getAmount(){
                                      return this.amount;
                           }
                  }





                                        syncronized
   sysnronized
volatile

              1               2
              100



                          0

                          0

                    100

                    100



   1


         2
Java.util.concurrent
import java.util.concurrent.atomic.*;

public class Account{
              private AtomicInteger amount;

              Account(int amount){
                              this.amount = new AtomicInteger(amount);
              }
              public int get(int amount){
                              if(this.amount.get() < amount){
                                             return 0;
                              }
                              do{
                                             if(this.amount.get() < amount){
                                                            break;
                                             }
                              } while(!this.amount.compareAndSet(this.amount.get(), this.amount.get() - amount));
                              return amount;
              }
              public void put(int amount){
                              do{
                                             if(amount < this.amount.get()){
                                                            break;
                                             }
                              } while(!this.amount.compareAndSet(this.amount.get(), this.amount.get() + amount));
              }

              public int getAmount(){
                             return amount.get();
              }
}
AtomicInteger
    public class AtomicInteger extends Number implements java.io.Serializable {
          private volatile int value;
          public AtomicInteger(int initialValue) {
                               value = initialValue;
          }
          public final int get() {
                               return value;
          }
          public final void set(int newValue) {
                               value = newValue;
          }
          public final int getAndSet(int newValue) {
                               for (;;) {
                                             int current = get();
                                             if (compareAndSet(current, newValue))
                                                           return current;
                               }
          }
          public final boolean compareAndSet(int expect, int update) {
                               return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
          }
    }
    CAS
    CAS
    Int                                                                         CAS
CAS   Compare And Swap

                1                          2
                100
                             0

                             0

                      100

                       CAS








     2                          0   CAS
          100
synchonize




volatile



JDK5.0       java.util.concurrent
                         Java
20070329 Java Programing Tips
20070329 Java Programing Tips

More Related Content

PPT
SDC - Einführung in Scala
Christian Baranowski
 
PPTX
String in .net
Larry Nung
 
PDF
The Ring programming language version 1.10 book - Part 44 of 212
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.7 book - Part 38 of 196
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.5.2 book - Part 32 of 181
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.9 book - Part 41 of 210
Mahmoud Samir Fayed
 
PDF
Scala by Luc Duponcheel
Stephan Janssen
 
SDC - Einführung in Scala
Christian Baranowski
 
String in .net
Larry Nung
 
The Ring programming language version 1.10 book - Part 44 of 212
Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 38 of 196
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 32 of 181
Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 41 of 210
Mahmoud Samir Fayed
 
Scala by Luc Duponcheel
Stephan Janssen
 

What's hot (20)

PDF
Coding in Style
scalaconfjp
 
PDF
Operator Overloading In Scala
Joey Gibson
 
ODP
Object Equality in Scala
Knoldus Inc.
 
PDF
The Ring programming language version 1.10 book - Part 46 of 212
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.5.3 book - Part 33 of 184
Mahmoud Samir Fayed
 
PPTX
Groovy grails types, operators, objects
Husain Dalal
 
PDF
자바 8 스트림 API
NAVER Corp
 
PDF
java sockets
Enam Ahmed Shahaz
 
PDF
Model-Driven Software Development - Static Analysis & Error Checking
Eelco Visser
 
PDF
The Ring programming language version 1.5.2 book - Part 33 of 181
Mahmoud Samir Fayed
 
PDF
JAVA 8 : Migration et enjeux stratégiques en entreprise
SOAT
 
PDF
The Ring programming language version 1.5.3 book - Part 34 of 184
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.6 book - Part 35 of 189
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.5 book - Part 6 of 31
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.4.1 book - Part 9 of 31
Mahmoud Samir Fayed
 
PDF
Scala for Java Developers - Intro
David Copeland
 
PDF
Javascript Uncommon Programming
jeffz
 
PDF
The Ring programming language version 1.2 book - Part 22 of 84
Mahmoud Samir Fayed
 
PPTX
Scala - where objects and functions meet
Mario Fusco
 
PDF
Java VS Python
Simone Federici
 
Coding in Style
scalaconfjp
 
Operator Overloading In Scala
Joey Gibson
 
Object Equality in Scala
Knoldus Inc.
 
The Ring programming language version 1.10 book - Part 46 of 212
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 33 of 184
Mahmoud Samir Fayed
 
Groovy grails types, operators, objects
Husain Dalal
 
자바 8 스트림 API
NAVER Corp
 
java sockets
Enam Ahmed Shahaz
 
Model-Driven Software Development - Static Analysis & Error Checking
Eelco Visser
 
The Ring programming language version 1.5.2 book - Part 33 of 181
Mahmoud Samir Fayed
 
JAVA 8 : Migration et enjeux stratégiques en entreprise
SOAT
 
The Ring programming language version 1.5.3 book - Part 34 of 184
Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 35 of 189
Mahmoud Samir Fayed
 
The Ring programming language version 1.5 book - Part 6 of 31
Mahmoud Samir Fayed
 
The Ring programming language version 1.4.1 book - Part 9 of 31
Mahmoud Samir Fayed
 
Scala for Java Developers - Intro
David Copeland
 
Javascript Uncommon Programming
jeffz
 
The Ring programming language version 1.2 book - Part 22 of 84
Mahmoud Samir Fayed
 
Scala - where objects and functions meet
Mario Fusco
 
Java VS Python
Simone Federici
 
Ad

Similar to 20070329 Java Programing Tips (20)

PDF
Sam wd programs
Soumya Behera
 
PPTX
CodeCamp Iasi 10 march 2012 - Practical Groovy
Codecamp Romania
 
KEY
ddd+scala
潤一 加藤
 
PDF
Scala 2013 review
Sagie Davidovich
 
PDF
OOP: Class Hierarchies
Atit Patumvan
 
ODP
Groovy intro for OUDL
J David Beutel
 
PDF
oop presentation note
Atit Patumvan
 
KEY
ぐだ生 Java入門第一回(equals hash code_tostring)
Makoto Yamazaki
 
PPTX
Clean code
James Brown
 
PPT
Oop lecture9 13
Shahriar Robbani
 
PDF
Practical Object-Oriented Back-in-Time Debugging
lienhard
 
PDF
Java 8 - Nuts and Bold - SFEIR Benelux
yohanbeschi
 
PDF
Google Guava - Core libraries for Java & Android
Jordi Gerona
 
PDF
The Groovy Way
Gabriel Dogaru
 
PDF
Java常见疑惑和陷阱
Ady Liu
 
PDF
Google guava
t fnico
 
DOC
Inheritance
آصف الصيفي
 
PDF
6. Generics. Collections. Streams
DEVTYPE
 
PDF
OOP: Classes and Objects
Atit Patumvan
 
DOCX
JAVAPGMS.docx
Mgm Mallikarjun
 
Sam wd programs
Soumya Behera
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
Codecamp Romania
 
ddd+scala
潤一 加藤
 
Scala 2013 review
Sagie Davidovich
 
OOP: Class Hierarchies
Atit Patumvan
 
Groovy intro for OUDL
J David Beutel
 
oop presentation note
Atit Patumvan
 
ぐだ生 Java入門第一回(equals hash code_tostring)
Makoto Yamazaki
 
Clean code
James Brown
 
Oop lecture9 13
Shahriar Robbani
 
Practical Object-Oriented Back-in-Time Debugging
lienhard
 
Java 8 - Nuts and Bold - SFEIR Benelux
yohanbeschi
 
Google Guava - Core libraries for Java & Android
Jordi Gerona
 
The Groovy Way
Gabriel Dogaru
 
Java常见疑惑和陷阱
Ady Liu
 
Google guava
t fnico
 
Inheritance
آصف الصيفي
 
6. Generics. Collections. Streams
DEVTYPE
 
OOP: Classes and Objects
Atit Patumvan
 
JAVAPGMS.docx
Mgm Mallikarjun
 
Ad

More from Shingo Furuyama (12)

PDF
ストリームデータに量子アニーリングを適用するアプリケーションフレームワークとその有用性
Shingo Furuyama
 
PDF
Hadoop Source Code Reading #17
Shingo Furuyama
 
PPT
Hadoop distributions as of 20131231
Shingo Furuyama
 
PDF
Askusa on AWS
Shingo Furuyama
 
PPTX
Askusa on aws
Shingo Furuyama
 
PPTX
Askusa on aws
Shingo Furuyama
 
PDF
Clojureのstm実装について
Shingo Furuyama
 
KEY
Asakusa Framework Tutorial β版
Shingo Furuyama
 
PDF
20070329 Tech Study
Shingo Furuyama
 
PDF
20070329 Object Oriented Programing Tips
Shingo Furuyama
 
PDF
#ajn6.lt.marblejenka
Shingo Furuyama
 
PDF
#ajn3.lt.marblejenka
Shingo Furuyama
 
ストリームデータに量子アニーリングを適用するアプリケーションフレームワークとその有用性
Shingo Furuyama
 
Hadoop Source Code Reading #17
Shingo Furuyama
 
Hadoop distributions as of 20131231
Shingo Furuyama
 
Askusa on AWS
Shingo Furuyama
 
Askusa on aws
Shingo Furuyama
 
Askusa on aws
Shingo Furuyama
 
Clojureのstm実装について
Shingo Furuyama
 
Asakusa Framework Tutorial β版
Shingo Furuyama
 
20070329 Tech Study
Shingo Furuyama
 
20070329 Object Oriented Programing Tips
Shingo Furuyama
 
#ajn6.lt.marblejenka
Shingo Furuyama
 
#ajn3.lt.marblejenka
Shingo Furuyama
 

Recently uploaded (20)

PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Architecture of the Future (09152021)
EdwardMeyman
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Software Development Methodologies in 2025
KodekX
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
This slide provides an overview Technology
mineshkharadi333
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Architecture of the Future (09152021)
EdwardMeyman
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Coupa-Overview _Assumptions presentation
annapureddyn
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Software Development Methodologies in 2025
KodekX
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 

20070329 Java Programing Tips

  • 1. Java TIPS
  • 4. String str1 = new String(“hoge”); String str2 = “hoge”; System.out.println(str1 == str2); System.out.println(str1.equals(str2)); False True
  • 5. == equals char[] value str1 str1 int length boolean equals(Object obj) char[] value str2 str2 int length boolean equals(Object obj) str1 == str2 str1 str2 char[] value str1.equals(str2)
  • 6. java.lang.String public final class String implements java.io.Serializable, Comparable<String>, CharSequence{ private final char value[]; private final int count; public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = count; if (n == anotherString.count) { char v1[] = value; char v2[] = anotherString.value; int i = offset; int j = anotherString.offset; while (n-- != 0) { if (v1[i++] != v2[j++]) return false; } return true; } } return false; }
  • 7. equals True False Account equals Account equals
  • 8. public abstract class Account{ private char[] custmorCode = new char[4]; Account(char[] custmorCode){ this.custmorCode = custmorCode; } public char[] getCustmorCode(){ return this.custmorCode; } @Override public boolean equals(Object obj){ // } }
  • 9. SavingAccount a1 = new SavingAccount(new char[]{‘0’,’1’,’2’,’3’}); SavingAccount a2 = new SavingAccount(new char[]{‘9’,’1’,’2’,’3’}); TimeDepositAccount a3 = new TimeDepositAccount(new char[]{‘0’,’1’,’2’,’3’}); TimeDepositAccount a4 = new TimeDepositAccount(new char[]{‘9’,’1’,’2’,’3’}); System.out.println(a1.equals(a3)); System.out.println(a2.equals(a4)); System.out.println(a1.equals(a2)); System.out.println(a2.equals(a3)); True True False False
  • 10. getClass instanceof boolean equals(Object obj) Object ClassCastException instanceof Class getClass() → true → true → false → true → false
  • 11. public abstract class Account{ // @Override public boolean equals(Object obj){ if(obj instanceof Account){ //if(getClass() == obj.getClass()){ char[] compareCode = ((Account)obj).getCustmorCode(); if(custmorCode.length != compareCode.length){ return false; } for(int i = 0; i<custmorCode.length; i++){ if(custmorCode[i] != compareCode[i]){ return false; } } return true; } else { return false; } } }
  • 13. equals java.lang.Object String char[] value equals Instanceof getClass equals
  • 15. CASE:
  • 16. Inspector Inspector 100ms
  • 17. Inspector Inspector 100ms
  • 18. Inspector Account  100ms  100ms  100ms  100ms  100ms CPU
  • 19. Inspector Inspector Inspector
  • 20. public class Account{ private byte[] lock = new byte[0]; private ArrayList<Inspector> targets = new ArrayList<Inspector>(); public int get(int amount){ synchronized(lock){ if(this.amount < amount){ return 0; } for(Inspector i : targets){ i.inspect(); } this.amount = this.amount - amount; return amount; } } public void addInspector(Inspector insp){ this.targets.add(insp); }  addInspector  Inspector
  • 21. CPU CPU
  • 23. String public class Main{ public static void main(String[] args){ String className = "RefrectionTest"; RefrectionTest rt = null; try{ rt = (RefrectionTest)Class .forName(className).newInstance(); } catch(Exception e) { } rt.dosth(); } } public class RefrectionTest{ public void dosth(){ System.out.println("Do Something"); } }
  • 24. String public class Main{ public static void main(String[] args){ String className = "RefrectionTest"; RefrectionTest rt = null; try{ rt = (RefrectionTest)Class.forName(className).newInstance(); } catch(Exception e) { } String methodName = "dosth"; Method method = null; try{ method = (Method)Class.forName(className) .getMethod(methodName,null); } catch(Exception e) { } method.invoke(Class.forName(className).newInstance(),null); } }
  • 26. import java.io.*; public class Main{ public static void main(String[] args){ Account a1 = new Account("hoge",5000); a1.get(100); try{ ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("hoge.ser")); oos.writeObject(a1); oos.close(); } catch(Exception e) {} System.out.println(a1); Account ser = null; try{ ObjectInputStream ois = new ObjectInputStream( new FileInputStream("hoge.ser")); ser = (Account)ois.readObject(); ois.close(); } catch(Exception e) {} ser.get(100); System.out.println(ser); } } public class Account implements Serializable{ // }
  • 29. 1 2 100 100 0 0 100 100   1 2
  • 30. synchronized public class Account{ private int amount; private byte[] lock = new byte[0]; Account(int amount){ this.amount = amount; } public int get(int amount){ synchronized(lock){ this.amount = this.amount - amount; return amount; } } public void put(int amount){ synchronized(lock){ this.amount = this.amount + amount; } } }  Synchonized:
  • 31. synchronized 1 2 100 100 0 100 0 200  2 1
  • 32. volatile public class Account{ private volatile int amount; Account(int amount){ this.amount = amount; } public int getAmount(){ return this.amount; } }   syncronized  sysnronized
  • 33. volatile 1 2 100 0 0 100 100  1  2
  • 34. Java.util.concurrent import java.util.concurrent.atomic.*; public class Account{ private AtomicInteger amount; Account(int amount){ this.amount = new AtomicInteger(amount); } public int get(int amount){ if(this.amount.get() < amount){ return 0; } do{ if(this.amount.get() < amount){ break; } } while(!this.amount.compareAndSet(this.amount.get(), this.amount.get() - amount)); return amount; } public void put(int amount){ do{ if(amount < this.amount.get()){ break; } } while(!this.amount.compareAndSet(this.amount.get(), this.amount.get() + amount)); } public int getAmount(){ return amount.get(); } }
  • 35. AtomicInteger public class AtomicInteger extends Number implements java.io.Serializable { private volatile int value; public AtomicInteger(int initialValue) { value = initialValue; } public final int get() { return value; } public final void set(int newValue) { value = newValue; } public final int getAndSet(int newValue) { for (;;) { int current = get(); if (compareAndSet(current, newValue)) return current; } } public final boolean compareAndSet(int expect, int update) { return unsafe.compareAndSwapInt(this, valueOffset, expect, update); } }  CAS  CAS  Int CAS
  • 36. CAS Compare And Swap 1 2 100 0 0 100 CAS    2 0 CAS 100
  • 37. synchonize volatile JDK5.0 java.util.concurrent Java