Make Java code run faster

Source: Internet
Author: User

This article briefly introduces some techniques used to make Java code more efficient during code writing.

1. place some system resources in the pool, such as database connections and threads. in standalone applications, database connection pools can be implemented using some open source connection pools, such as c3p0, proxool, and DBCP. Applications Running in containers can use datasource provided by the server. the thread pool can use Java provided by JDK itself. util. concurrent. executorservice.

import java.util.concurrent.Executors;  import java.util.concurrent.ExecutorService;  public class JavaThreadPool {      public static void main(String[] args) {      ExecutorService pool = Executors.newFixedThreadPool(2);            Thread t1 = new MyThread();      Thread t2 = new MyThread();      Thread t3 = new MyThread();      Thread t4 = new MyThread();      Thread t5 = new MyThread();       pool.execute(t1);      pool.execute(t2);      pool.execute(t3);      pool.execute(t4);       pool.shutdown();      }  }   class MyThread extends Thread {      public void run() {      System.out.println(Thread.currentThread().getName() + "running....");      }  } 

2. Reduce network overhead. when interacting with a database or remote service, try to merge multiple calls into one call.

3. cache frequently accessed external resources to the memory. You can simply use static hashmap to load resources when the application is started, or use some open-source cache frameworks, such as Oscache and ehcache. for synchronization with resources, you can take the initiative to notify users of regular polling and external resource updates. you can also set aside interfaces (command or interface) in your own code for manual synchronization.

4. Optimized I/O operations. When operating files in Java, it is divided into two types: inputstream and outputstream, reader and writer. The stream method is faster. The latter is mainly used for operating characters, stream can be used to improve efficiency when the character is only ASCII. after jdk1.4, NiO is more efficient than Io.

    OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("d:/temp/test.txt")));                  out.write("abcde".getBytes());            out.flush();      out.close(); 

Use bufferedinputstream, bufferedoutputstream, bufferedreader, and bufferedwriter to reduce the number of direct access requests to the disk.

    FileReader fr = new FileReader(f);      BufferedReader br = new BufferedReader(fr);      while (br.readLine() != null) count++; 

5. Do not use the singleton mode for classes that only require one instance in the entire application. for string connection operations, use stringbuffer or stringbuilder. utility Classes are accessed through static methods.

6. Avoid using incorrect methods. For example, exception can control the release of methods, but exception must keep stacktrace consumption performance. Unless necessary, do not use instanceof for conditional judgment. Try to use ratio conditional judgment. use a Java class with a high efficiency. For example, arraylist has better performance than vector.

7. performance considerations should be considered at the beginning of system analysis and design.

In short, the performance of a system is optimized from three main aspects: CPU, memory, and Io. reduce Unnecessary CPU consumption, reduce unnecessary Io operations, and increase memory utilization efficiency.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.