Programing/Java

Guava Java 라이브러리

BUST 2017. 7. 2. 21:25

Guava Java 라이브러리

Guava Java 라이브러리에서 자주 사용되는 기능을 정리해보자.

EventBus

Sample Code

// Class is typically registered by the container. 
class EventBusChangeRecorder {
  @Subscribe
  public void recordCustomerChange(ChangeEvent e) {
    recordChange(e.getChange());
  }
}
 
// somewhere during initialization 
eventBus.register(new EventBusChangeRecorder());
 
// much later 
public void changeCustomer() {
  ChangeEvent event = getChangeEvent();
  eventBus.post(event);
}

Cache

LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
       .maximumSize(1000)
       .expireAfterWrite(10, TimeUnit.MINUTES)
       .removalListener(MY_LISTENER)
       .build(
           new CacheLoader<Key, Graph>() {
             public Graph load(Key key) throws AnyException {
               return createExpensiveGraph(key);
             }
           });

Collections, Lists, Maps Utils

static constructors

List<TypeThatsTooLongForItsOwnGood> list = Lists.newArrayList();
Map<KeyType, LongishValueType> map = Maps.newLinkedHashMap();

I/O

Stream Close 문제점

InputStream in = null;
try {
  in = openInputStream();
  OutputStream out = null;
  try {
    out = openOutputStream();
    // do something with in and out 
  } finally {
    if (out != null) {
      out.close();
    }
  }
} finally {
  if (in != null) {
    in.close();
  }
}
  • try/catch 문이 얽혀져 있다.

해결방법

try/catch resource
try (InputStream in = openInputStream();
     OutputStream out = openOutputStream(){
  // do stuff with in and out 
}

Source and Sink
ByteSink sink = ...
Files.asByteSource(file).copyTo(sink);

Closer in guava library
Closer closer = Closer.create();
try {
  InputStream in = closer.register(openInputStream());
  OutputStream out = closer.register(openOutputStream());
  // do stuff with in and out 
} catch (Throwable e) { // must catch Throwable 
  throw closer.rethrow(e);
} finally {
  closer.close();
}

Strings

  • Joiner
Joiner.on(",").join(Arrays.asList(1, 5, 7)); // returns "1,5,7" 
  • Splitter
Splitter.on(',')
    .trimResults()
    .omitEmptyStrings()
    .split("foo,bar,,   qux");

Reference