4.不要なオブジェクトの作成を禁止


Boxing TypeではなくPrimitive Typeを使用することを推奨します
    public static long primitive() {
        long num = 0L;
        for (long i = 0; i <= Integer.MAX_VALUE; i++) {
            num += i;
        }
        return num;
    }

    public static long boxing() {
        Long num = 0L;
        for (long i = 0; i <= Integer.MAX_VALUE; i++) {
            num += i;
        }
        return num;
    }
  • Nullの値が必要な場合、Boxingタイプは必要ありません.Primitiveタイプを考慮します.
    ->パフォーマンスの違い
  • 注意が必要な組み込み方法
    matchesメソッドはpatternオブジェクトの生成を続けます.
    public static boolean matches(String regex, CharSequence charSequence) {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(charSequence);
            return m.matches();
    }
  • ソリューション
    ->Pattern instance
  • のみ作成
    public class EmailUtil {
            private static final Pattern EMAIL = Pattern.compile("[a-zA-Z0-9.-]\\\\.[a-zA-Z]{2,6}$");
            static boolean isEmail(String string) {
                return EMAIL.matcher(string).matches();
            }
    }
    Finalizer
  • 非特殊の場合は
  • を無効にする.
  • セキュリティネットワークロールのみ
  • を使用
    public class Test {
    
        private boolean closed;
        public void close() throws Exception {
            // 객체 닫기
        }
        
        @Override // 안전망
        protected void finalize() throws Throwable {
            if (!this.closed) {
                close();
            }
        }
    }
    try-with-resourcesではなくtry-finally
  • 内部でExceptionが発生した場合に上書きされ、追跡が困難となる.
  • try-finally
    public class Test {
    
        static void copy(String s1, String s2) throws IOException {
            InputStream inputStream = new FileInputStream(s1);
            try {
                OutputStream outputStream = new FileOutputStream(s1);
                try {
                    byte[] bytes = new byte[100];
                    int num;
                    while ((num = inputStream.read(bytes)) >= 0) {
                        outputStream.write(bytes, 0, num);
                    }
                } finally {
                    outputStream.close();
                }
            } finally {
                inputStream.close();
            }
        }
    }
    try-with-resources

  • 自動化実装後にTestクラス(@Override Close()を使用

  • 簡単なEx)
  • try (Test test1 = new Test();
         Test test2 = new Test();)
            {
                // Exception
            }
  • try-finallyとtry-with-resources比較
  • @Slf4j
    public class SubTest {
    
        public void noTWR() throws IOException {
    
            FileInputStream file = null;
            BufferedInputStream buffer = null;
            try {
                file = new FileInputStream("file.txt");
                buffer = new BufferedInputStream(file);
                int data = -1;
                while ((data = buffer.read()) != -1) {
                    log.info("data = {}", (char) data);
                }
            } finally {
                // 객체 닫기
                if (file != null) {
                    file.close();
                }
                if (buffer != null) {
                    buffer.close();
                }
            }
        }
        
        public String useTWR(String url) throws IOException {
    
            URL targetUrl = new URL(url);
    
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(targetUrl.openStream()))) {
                StringBuffer buffer = new StringBuffer();
                String tmp = null;
    
                while ((tmp = reader.readLine()) != null) {
                    buffer.append(tmp);
                }
                return buffer.toString();
            }
        }
    }
  • FileInputStreamとBufferInputStreamはInputStreamを継承し、自動再利用性を実現するため、リソースの使用を試みることができます.
  • try文の終了時に自動的に閉じられます.これにより、コードの簡素化とメンテナンスが容易になります.
  • Cleaner & try-with-resources
  • Cleanが失敗する場合、自動Closeableを使用して補足
  • を行うことができる.
    public class Test implements AutoCloseable {
    
        private static final Cleaner cleaner = Cleaner.create();
        private static class CleanData implements Runnable {
            @Override
            public void run() {
                // clean
            }
        }
        private final CleanData cleanData;
        private final Cleaner.Cleanable cleanable;
    
        public Test() {
            this.cleanData = new CleanData();
            this.cleanable = cleaner.register(this, cleanData);
        }
    
        @Override
        public void close() {
            cleanable.clean();
        }
    }
    出典:[本factive java]