Languages
 
 
 
 
Навигация
 
 
 
 
 
 

Little more about Java I/O Performance

  Tagged

Working on performance in one of java projects I found that the slowest part is copy method from file utility class. Method was implemented without buffering. Implementation was next: just using ‘while’ operator reading input stream and writing to output stream.

There are good article about i/o performance on sun website.

Listing 4-4 from article looks good, but provided method not perfect too. I have next reason: my application is a multithreaded application. And anytime I synchronize on a static field, I make a bottleneck, because all threads must block while waiting to enter the synchronized block of code.

There is solution for this. If you want to use a cache that is not initialized every time method invoked, you should use ThreadLocal, and a weak reference to the buffer, which allows the memory to be collected when memory is tight.

So result code next:

import java.io.*;

public class CopyExample {
  // Thread buffer size
  private static final int BUFF_SIZE = 1024 * 4;

  // Thread buffer variable
  private static final ThreadLocal<byte[]> buffCache = new ThreadLocal<byte[]>() {
    @Override
    protected byte[] initialValue() {
      return new byte[BUFF_SIZE];
    }
  };

  private CopyExample() {
  }

  public static void copy(File from, File to) throws IOException {
    InputStream in = null;
    OutputStream out = null;
    try {
      in = new FileInputStream(from);
      out = new FileOutputStream(to);
      byte[] buffer = buffCache.get();
      int amountRead;
      while ((amountRead = in.read(buffer)) != -1) {
        out.write(buffer, 0, amountRead);
      }
    } finally {
      // close in and out streams
      // ...
    }
  }
}

If you have some notes about this code, please make comment to this post. It's intresting to know other opinions.


Настройки просмотра комментариев

Выберите нужный метод показа комментариев и нажмите "Сохранить установки".

Great tips, add to bookmark.

Great tips, add to bookmark. Thanks.

Отправить комментарий

Содержание этого поля является приватным и не предназначено к показу.
  • Допускаются только следующие теги HTML: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>

Подробнее о форматировании

 
 
 
 
 
 
  • hooligan
  • cupuyc
  • ESoImk
  • LeKz
  • Anton
 
 
 
© 2006-2008 kobyleha.com