Concurrent Programming을 위한 Java의 Concurrency Utilities

27 Comments

Sun의 Java White Papers에서 Java의 Concurrency Utilites에 대한 글이 있어서 포스팅한다.

Concurrent Programming을 C/C++ 등의 언어에서 생각하면, 일단, legacy code나 reference code 또는 자신이 정리해둔 코드가 없다면 귀차니즘이 발동함과 동시에 (설령 베이스 코드들이 있다고 하더라도) 온갖 에러들 (race condition 등)과 맞서 싸울 준비를 해야한다.

Java에서는 이런 것들이 한결 쉬울 것이다. 별 생각 없이 쉽게 쓴다는 이 점 보다는 좀 더 가치 있는 것을 생각할 시간을 제공해주는 이점이 있다.

아무튼, 여지 껏 Java 보다는 C/C++에 더 친숙해 있고, Java의 thread나 synchronized, timing 등을 별 생각 없이 사용했는데, Java Concurrency Utitlites White Paper를 보니 또 한 번 우물안 개구리를 느끼게 해준다.

Performance를 향상할 수 있고 여러 가지 측면에서 추천하는 방법들을 알 수 있어 유익한 것 같다.

Concurrency Utilities Overview

위 문서 중에서 제공되는 Features들만 나열해보면 다음과 같다.

  • Task Scheduling Framework – The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies. Implementations are provided that allow tasks to be executed within the submitting thread, in a single background thread (as with events in Swing), in a newly created thread, or in a thread pool, and developers can create of Executor supporting arbitrary execution policies. The built-in implementations offer configurable policies such as queue length limits and saturation policy which can improve the stability of applications by preventing runaway resource consumption.
  • Concurrent Collections – Several new Collections classes have been added, including the new Queue and BlockingQueue interfaces, and high-performance, concurrent implementations of Map, List, and Queue.
  • Atomic Variables – Classes for atomically manipulating single variables (primitive types or references), providing high-performance atomic arithmetic and compare-and-set methods. The atomic variable implementations in java.util.concurrent.atomic offer higher performance than would be available by using synchronization (on most platforms), making them useful for implementing high-performance concurrent algorithms as well as conveniently implementing counters and sequence number generators.
  • Synchronizers – General purpose synchronization classes, including semaphores, mutexes, barriers, latches, and exchangers, which facilitate coordination between threads.
  • Locks – While locking is built into the Java language via the synchronized keyword, there are a number of inconvenient limitations to built-in monitor locks. The java.util.concurrent.locks package provides a high-performance lock implementation with the same memory semantics as synchronization, but which also supports specifying a timeout when attempting to acquire a lock, multiple condition variables per lock, non-lexically scoped locks, and support for interrupting threads which are waiting to acquire a lock.
  • Nanosecond-granularity timing – The System.nanoTime method enables access to a nanosecond-granularity time source for making relative time measurements, and methods which accept timeouts (such as the BlockingQueue.offer, BlockingQueue.poll, Lock.tryLock, Condition.await, and Thread.sleep) can take timeout values in nanoseconds. The actual precision of System.nanoTime is platform-dependent.

Java 언어 특징에 대해서 잘 정리한 글 (JavaSCript,C/C++과의 비교)과 Ada와 OOP에 대해서 비교한 논문

2 Comments

Java 언어 자체의 특징에 대해서 잘 정리해둔 글들이 있어서 포스팅한다.

아래 글은 Sun의 white paper들을 보고 Java의 특징들을 요약했고 JavaScript, C/C++과도 잘 비교해두었다.

CHARACTERISTICS OF JAVA

그리고 아래 논문은 Java와 Ada 95를 OOP 관점에서 잘 비교해둔 논문이다.

시간을 내어 찬찬히 읽어보면 좋을 것이다. OOP 자체에 대해서도 좀 더 Program Language 차원에서 접근해 볼 수 있다.

A Comparison of the Object-Oriented Features of Ada 95 and Java

[Java] HashMap을 쓸 것인가 Hashtable을 쓸 것인가??

No Comments

몇 년 동안 Java를 손에서 놓았고 C++을 하다 최근 다시 Java를 하려니 적응하기가 힘들다. Eclipse와 함께 너무나 편안하고 설계까지 깔끔하게 잘되었다고 생각이 들면서도 가끔 어떤 부분들은 (생각해보고 또 생각해보면 맞지만) 이해가 쉽지 않은 부분도 있다.

아무튼 std::map을 대처하기 위해 HashMap을 쓸 것인가? Hashtable을 쓸 것인가?

예전에 별생각도 안 하고 먼저 떠오르는 데로 쓴 것 같다.

결론부터 말하면 (예전에 그랬던 것처럼) 별생각 없이 쓴다면 HashMap을 쓰면 될 것이다.

그리고 HashMap과 Hashtable의 Java Doc을 보고 정리하면,

HashMap 기준에서 Hashtable과 비교하면

1. HashMap은 key와 value에 null을 허용하지만 Hashtable은 그렇지 않다.

2. HashMap은 thread safe하지 않고 (not synchronized) Hashtable은 그렇다 (synchronized). 진정한 Java인이라면 미래를 위해 Hashtable을 쓰는 게 맞을 것 같기도 하다.
HashMap 자체는 not synchronized하기 때문에 다음과 같이 Collection.synchronizedMap을 이용해서 synchronized하게 만들 수 있다.

Map m = Collections.synchronizedMap(new HashMap(...));

3. HashMap은 bucket에 element들을 흩어뿌리기 때문에 get/put과 같은 기본 동작들이 동일한 시간 (constant-time performance) 에 수행된다.

HashMap과 Hashtable에서 둘 다 고려할 사항은

1. capacity와 load factor

Capacity는 bucket의 수이고 load factor는 bucket의 element가 얼만큼 찼을 경우 rehash를 발생 시킬 것인지를 정하는 것이다. rehash의 경우는 bucket의 수가 두 배로 늘어나고 각 element에 대해서 hash가 다시 일어나는 것을 의미하기 때문에 이 것은 시간-공간의 trade-off가 있다.

Load factor는 0.75를 HashMap과 Hashtable에서 둘다 ideal number로 권장하고 default value이다.

Capacity는 HashMap은 default value가 16이고 Hashtable은 11이다.

생성할 때 아주 많은 (얼만큼인지는 제시하지 않고 있다) element가 삽입될 것이라면 capacity를 초기에 높게 잡는게 좋을 것 같다.

2. ConcurrentModificationException

Iterator를 얻은 후에 Iterator를 통하지 않고 외부에서 element가 삭제되거나 추가되면 ConcurrentModificationException이 발생한다 (fail-fast라고 한다. 문제가 생기면 바로 보고하는 것으로 fail-stop이라고 한다). 당연한 말이겠지만, fail-fast로 인한 exception handling을 통해 기능을 수행하는 코드를 작성하지 말고 말 그대로 bug를 찾기 위해 이를 이용해라고 한다.

아무튼 오래 만에 JavaDoc을 자세히 읽어 본거 같다. 프로그램에서 많은 것들이 중요할 것이고 그 중 자료 구조 (특히 자바와 같은 언어에서)도 많은 것을 고려해야 하기에 포스트를 지루하게 써보았다.

“별 생각 없이 쓴다” 라는 말 자체를 이미 거론해 버렸지만 그리고 그 목적으로 HashMap을 거론했지만, “별 생각 없이 쓴다” 라는 말 자체는 (그리고 그 “별 생각 없이 쓴 것”들이 많아 질 수록) 미래의 재앙을 키워가는 것이기 때문에 지양 해야 할 것이다.

[Ref]

HashMap Java Doc SE6: http://java.sun.com/javase/6/docs/api/java/util/HashMap.html

Hashtable Java Doc SE6: http://java.sun.com/javase/6/docs/api/java/util/Hashtable.html

Fail-fast (Fail-stop): http://en.wikipedia.org/wiki/Fail-fast

[OSGi] OSGi와 Equinox 관련 Reference

3 Comments

2003년부터 인연이 생겨 (꾸준히는 아니지만) OSGi를 경험하고 있다.

Home이나 Mobile, Automobile등을 위한 networking의 platform 뿐만 아니라 Application Framework (e.g. Eclipse)으로써도 훌륭하다.

참고 자료 몇 가지를 포스팅한다.

* Equinox Project Homepage
    http://www.eclipse.org/equinox/

* Equinox osgi download
    http://download.eclipse.org/eclipse/equinox/

* OSGi Home Page
    http://www.osgi.org/Main/HomePage

* Eclipse 사용자 공간으로 OSGi 관련 좋은 내용도 많다.
   http://www.eclipsezone.com

[eclipse] ClearCase plug-in

21 Comments

Eclipse의 ClearCase plug-in 중 아래 플러그인이 심플하고 괜찮은 것 같다.

Eclipse ClearCase Integration

물론, mylyn (trac), svn을 쓰고 있지만.. CC도 써야하는 상황이라…

Older Entries