SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Downloaden Sie, um offline zu lesen
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

Weitere Àhnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 
Lezione03
Lezione03Lezione03
Lezione03
robynho86
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
wpgreenway
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
futurespective
 
Thread
ThreadThread
Thread
phanleson
 
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
 

Ähnlich wie 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)
 

Mehr von 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 Tech Study
20070329 Tech Study 20070329 Tech Study
20070329 Tech Study
Shingo Furuyama
 
20070329 Object Oriented Programing Tips
20070329 Object Oriented Programing Tips20070329 Object Oriented Programing Tips
20070329 Object Oriented Programing Tips
Shingo Furuyama
 
#ajn6.lt.marblejenka
#ajn6.lt.marblejenka#ajn6.lt.marblejenka
#ajn6.lt.marblejenka
Shingo Furuyama
 

Mehr von 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
 

KĂŒrzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
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
 

KĂŒrzlich hochgeladen (20)

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...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
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)
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 

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