SlideShare a Scribd company logo
1 of 39
Download to read offline
Java   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;
                   }
         }
}
equals
java.lang.Object             String
           char[] value

equals                    Instanceof
         getClass          equals
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
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);
         }
}
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{      //        }
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

What's hot

Model-Driven Software Development - Static Analysis & Error Checking
Model-Driven Software Development - Static Analysis & Error CheckingModel-Driven Software Development - Static Analysis & Error Checking
Model-Driven Software Development - Static Analysis & Error Checking
Eelco Visser
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
jeffz
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
 

What's hot (20)

Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Operator Overloading In Scala
Operator Overloading In ScalaOperator Overloading In Scala
Operator Overloading In Scala
 
Object Equality in Scala
Object Equality in ScalaObject Equality in Scala
Object Equality in Scala
 
The Ring programming language version 1.10 book - Part 46 of 212
The Ring programming language version 1.10 book - Part 46 of 212The Ring programming language version 1.10 book - Part 46 of 212
The Ring programming language version 1.10 book - Part 46 of 212
 
The Ring programming language version 1.5.3 book - Part 33 of 184
The Ring programming language version 1.5.3 book - Part 33 of 184The Ring programming language version 1.5.3 book - Part 33 of 184
The Ring programming language version 1.5.3 book - Part 33 of 184
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
 
자바 8 스트림 API
자바 8 스트림 API자바 8 스트림 API
자바 8 스트림 API
 
java sockets
 java sockets java sockets
java sockets
 
Model-Driven Software Development - Static Analysis & Error Checking
Model-Driven Software Development - Static Analysis & Error CheckingModel-Driven Software Development - Static Analysis & Error Checking
Model-Driven Software Development - Static Analysis & Error Checking
 
The Ring programming language version 1.5.2 book - Part 33 of 181
The Ring programming language version 1.5.2 book - Part 33 of 181The Ring programming language version 1.5.2 book - Part 33 of 181
The Ring programming language version 1.5.2 book - Part 33 of 181
 
JAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entrepriseJAVA 8 : Migration et enjeux stratégiques en entreprise
JAVA 8 : Migration et enjeux stratégiques en entreprise
 
The Ring programming language version 1.5.3 book - Part 34 of 184
The Ring programming language version 1.5.3 book - Part 34 of 184The Ring programming language version 1.5.3 book - Part 34 of 184
The Ring programming language version 1.5.3 book - Part 34 of 184
 
The Ring programming language version 1.6 book - Part 35 of 189
The Ring programming language version 1.6 book - Part 35 of 189The Ring programming language version 1.6 book - Part 35 of 189
The Ring programming language version 1.6 book - Part 35 of 189
 
The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31The Ring programming language version 1.5 book - Part 6 of 31
The Ring programming language version 1.5 book - Part 6 of 31
 
The Ring programming language version 1.4.1 book - Part 9 of 31
The Ring programming language version 1.4.1 book - Part 9 of 31The Ring programming language version 1.4.1 book - Part 9 of 31
The Ring programming language version 1.4.1 book - Part 9 of 31
 
Scala for Java Developers - Intro
Scala for Java Developers - IntroScala for Java Developers - Intro
Scala for Java Developers - Intro
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
 
The Ring programming language version 1.2 book - Part 22 of 84
The Ring programming language version 1.2 book - Part 22 of 84The Ring programming language version 1.2 book - Part 22 of 84
The Ring programming language version 1.2 book - Part 22 of 84
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 

Similar to 20070329 Java Programing Tips

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
Sagie Davidovich
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
wpgreenway
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
Codecamp Romania
 

Similar to 20070329 Java Programing Tips (20)

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
OBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptOBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .ppt
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Java programs
Java programsJava programs
Java programs
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
 
Thread
ThreadThread
Thread
 
Oop lecture9 13
Oop lecture9 13Oop lecture9 13
Oop lecture9 13
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Lec2
Lec2Lec2
Lec2
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 

More from Shingo Furuyama

Hadoop distributions as of 20131231
Hadoop distributions as of 20131231Hadoop distributions as of 20131231
Hadoop distributions as of 20131231
Shingo Furuyama
 
Clojureのstm実装について
Clojureのstm実装についてClojureのstm実装について
Clojureのstm実装について
Shingo Furuyama
 
20070329 Object Oriented Programing Tips
20070329 Object Oriented Programing Tips20070329 Object Oriented Programing Tips
20070329 Object Oriented Programing Tips
Shingo Furuyama
 

More from Shingo Furuyama (12)

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

Recently uploaded

Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
FIDO Alliance
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
UK Journal
 

Recently uploaded (20)

WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties ReimaginedEasier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
 

20070329 Java Programing Tips

  • 1. Java TIPS
  • 3.
  • 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; } } }
  • 12.
  • 13. equals java.lang.Object String char[] value equals Instanceof getClass equals
  • 14.
  • 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
  • 22.
  • 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); } }
  • 25.
  • 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{ // }
  • 27.
  • 28.
  • 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