'java core' 카테고리의 다른 글

jdk 6 update 24 중요 설치  (0) 2011.02.22
jdk contant value 모음  (0) 2011.02.08
HashMap 사용시 cpu 많이 소요되는 현상  (0) 2011.01.10
OOME 검출 방법  (0) 2011.01.06
vebose:gc 를 파일 로그로 남기기  (0) 2010.11.22
Posted by '김용환'
,


hashMap을 사용하는 곳에서 cpu를 많이 소요하는 부분이 발견되었다.


1. freemarker 예제

 

"TP-Processor215" daemon prio=10 tid=0x55476000 nid=0xfab runnable [0x5495c000]

   java.lang.Thread.State: RUNNABLE

    at java.util.HashMap.get(HashMap.java:303)

    at freemarker.core.RegexBuiltins.getPattern(RegexBuiltins.java:77)

    at freemarker.core.RegexBuiltins$MatcherBuilder.exec(RegexBuiltins.java:277)

    at freemarker.core.MethodCall._getAsTemplateModel(MethodCall.java:93)

    at freemarker.core.Expression.getAsTemplateModel(Expression.java:89)

    at freemarker.core.Expression.isTrue(Expression.java:138)

 

"TP-Processor61" daemon prio=10 tid=0x08fe5800 nid=0x35f9 runnable [0x52575000]

   java.lang.Thread.State: RUNNABLE

    at java.util.HashMap.get(HashMap.java:303)

    at freemarker.core.RegexBuiltins.getPattern(RegexBuiltins.java:77)

    at freemarker.core.RegexBuiltins$MatcherBuilder.exec(RegexBuiltins.java:277)

    at freemarker.core.MethodCall._getAsTemplateModel(MethodCall.java:93)

    at freemarker.core.Expression.getAsTemplateModel(Expression.java:89)

    at freemarker.core.Expression.isTrue(Expression.java:138)

    at freemarker.core.NotExpression.isTrue(NotExpression.java:66)

    at freemarker.core.ParentheticalExpression.isTrue(ParentheticalExpression.java:66)

    at freemarker.core.ConditionalBlock.accept(ConditionalBlock.java:77)

    at freemarker.core.Environment.visit(Environment.java:208)

    at freemarker.core.MixedContent.accept(MixedContent.java:92)

    at freemarker.core.Environment.visit(Environment.java:208)

    at freemarker.core.IfBlock.accept(IfBlock.java:82)


2. 사용자 개발 코드에서 hashmap 사용

"TP-Processor16" daemon prio=10 tid=0x6b2f9400 nid=0x2264 runnable [0x6a45b000]
   java.lang.Thread.State: RUNNABLE
        at java.util.HashMap.put(HashMap.java:374)



둘다 HashMap을 사용한 것인데..
아래 beautiful race condtion이라는 블로그에서 hashmap을 사용하면서 문제가 있을만한 부분을 소개했다.

http://mailinator.blogspot.com/2009/06/beautiful-race-condition.html

간단하게 말하면..

Thread1과 Thread2가 resize() 메소드로 들어왔는데..Thread1 이 한 중간에 멈추어졌고, Thread2는 resize를 한 경우에 생길 수 있는 부분을 설명하였다..

1:  // Transfer method in java.util.HashMap -
2:  // called to resize the hashmap
3:  
4:  for (int j = 0; j < src.length; j++) {
5:    Entry e = src[j];
6:    if (e != null) {
7:      src[j] = null;
8:      do {
9:      Entry next = e.next;
     // Thread1 STOPS RIGHT HERE
10:
     int i = indexFor(e.hash, newCapacity);
11:     e.next = newTable[i];
12:     newTable[i] = e;
13:     e = next;
14:   } while (e != null);
15:   }
16: }





Thread 1이 resize 메소드의 9줄까지 실행했다고 가정.

Thread2는 resize 메소드를 다 실행하였다.


즉, A-> B를 가르키고, 있고, B->A를 가르키는 상태이다.

Thread1이 처리를 완료하면서.A-><-B가 되면서..

map에 저장되던 데이터들이 cross refererence되어서 무한 루프에 걸리는 현상이 발견되었다.



HashMap의  get, put 메소드를 본다.
즉, entry가 null일 때까지 for문을 돌릴 수 밖에 없는 구조이기 때문에, 계속 돌아가는 구조이다.


    public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }


    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        int hash = hash(key.hashCode());
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
                return e.value;
        }
        return null;
    }



따라서, HashMap은 동기화 문제가 발생될 수 있는 곳에 사용해서는 안된다. 차라리 ConcurrentHashMap을 쓰는 것이 맞다.  그게 싫다면, HashMap을 쓸 떄, 프레임웍을 쓰든, 잘 사용하면 좋을 수도 있겠다.


Synchronized hashmap 과 ConcurrentHashMap의 성능에 대한 블로그가 있다.
http://unserializableone.blogspot.com/2007/04/performance-comparision-between.html


요즘에. Apache Common 개발자들이 synchronized HashMap보다는 ConcurrentHashMap을 더 많이 사용하려는 움직임이 있다.

https://issues.apache.org/jira/browse/HTTPCLIENT-903
http://www.mail-archive.com/dev@commons.apache.org/msg18926.html


@comment
ConcurrentHashMap이 SynchronizedHashMap보다 성능이 훨씬 좋거나. 비슷하다. 따라서, ConcurrentHashMap 에 대한 성능차이가 거의 없다면 써도 무방하지 않을까 생각이 든다.

'java core' 카테고리의 다른 글

jdk contant value 모음  (0) 2011.02.08
jdbc specification 보기  (0) 2011.02.07
OOME 검출 방법  (0) 2011.01.06
vebose:gc 를 파일 로그로 남기기  (0) 2010.11.22
안드로이드 코딩 가이드 중 Designing for Performance  (0) 2010.10.04
Posted by '김용환'
,

OOME 검출 방법

java core 2011. 1. 6. 09:43


 

 Memory leak 검출 기능
5~10번의 Major GC가 일어나는 동안에 여유 메모리의 감소가 연속적으로 발생되면 OOME가 날 가능성이 많다. 이 정보를 캐취해서 전달하면 된다.


Posted by '김용환'
,

  • verbose:gc
    This flag turns on the logging of GC information. Available from J2SE1.3.

  • -Xloggc=filename
    This switch can be used to specify the name of the log file where the "verbose:gc" information can be logged instead of standard output. Available from J2SE1.4.

    출처 : http://java.sun.com/developer/technicalArticles/Programming/turbo/
  • Posted by '김용환'
    ,

    Designing for Performance


    http://developer.android.com/guide/practices/design/performance.html


     

     

    There are three aphorisms concerning optimization that everyone should know. They are perhaps beginning to suffer from overexposure, but in case you aren't yet familiar with them, here they are:

    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason—including blind stupidity.

    —William A. Wulf 1

    We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

    —Donald E. Knuth 2

    We follow two rules in the matter of optimization:

    • Rule 1. Don't do it.
    • Rule 2 (for experts only). Don't do it yet — that is, not until you have a perfectly clear and unoptimized solution.

    —M. A. Jackson 3



    'java core' 카테고리의 다른 글

    OOME 검출 방법  (0) 2011.01.06
    vebose:gc 를 파일 로그로 남기기  (0) 2010.11.22
    common pool 2.x 로 고고!  (0) 2010.10.01
    자바 소스 설치하기  (0) 2010.10.01
    java checked Exception에 대한 고찰  (0) 2010.10.01
    Posted by '김용환'
    ,


    Apache Commons 의 common pool이 1.5.x  버젼이 Release되고 있습니다.

     

    commons pool 2.0 을 만들자고 얘기가 메일링 리스트에서 진행중입니다. 다들 환영하고 있는 분위기네요..

    내용은 다음과 같습니다.

     

     0) Generification (POOL-83)
     1) Replace wait/notify with 1.5+ thread management
     2) JMX instrumentation and management
     3) Remove deprecated methods
     4) Instance tracking (holding references to instances under management and tracking events of interest from them - meeting DBCP  AbanonedObjectPool requirement)
     5) Clean up and extend pool maintenance


    아 참여하고 파...

    Posted by '김용환'
    ,

    Jdk 1.6 update 22를 기준으로 설명

    1. http://download.java.net/jdk6/6u10/archive/ 접속해서 jar로 된 소스를 다운받는다.
      버젼에 따라 다르게 설치되는데.. linux os를 기준으로 한다.
    2. 다운받은 jar를 푼다.
    3. cmd창을 열어서 다운받은 jar 밑에서 다음을 실행
     java -classpath .  com.sun.tools.extractor.Installer 

    4.  swing ui가 lauch됨. 사용에 대한 정책에 대해서 읽어보고, accept를 선택 
       (update 22는 있었는데,   update 25는 정책이 없네?? )
    5. 설치 디렉토리 선택
    6. 설치 되는 것보고, 완료 확인함.

    spac, x86, zero, ia64를 기반으로 된 소스만 있는 것 같음..




    'java core' 카테고리의 다른 글

    안드로이드 코딩 가이드 중 Designing for Performance  (0) 2010.10.04
    common pool 2.x 로 고고!  (0) 2010.10.01
    java checked Exception에 대한 고찰  (0) 2010.10.01
    Java option 관련  (0) 2010.08.31
    java -server  (0) 2010.08.19
    Posted by '김용환'
    ,


    Exceptional Java by Alan Griffiths
    http://www.octopull.demon.co.uk/java/ExceptionalJava.html

    Bruce Eckle  Does Java need Checked Exceptions
    http://www.mindview.net/Etc/Discussions/CheckedExceptions

    Rod johnson
    expert one-on-one j2ee설계와 개발

    'java core' 카테고리의 다른 글

    common pool 2.x 로 고고!  (0) 2010.10.01
    자바 소스 설치하기  (0) 2010.10.01
    Java option 관련  (0) 2010.08.31
    java -server  (0) 2010.08.19
    G1 알고리즘 공부  (0) 2010.08.09
    Posted by '김용환'
    ,

    Java option 관련

    java core 2010. 8. 31. 21:27

    정리차원에서 글 써본다.
    java -server 옵션은 지난번에 썻고.
    java 의 디폴트 initial heap size는 physical memory의 1/64 이다. maximum heap size는 physcal memory의 1/4 이다.

    만약 physical memory가 4G이면, initial heap size는 62Mbyte이고 max heap size는 1G이다.

    또한 GC 옵션은  UseParallelGC이다.



    http://download.oracle.com/javase/6/docs/technotes/guides/vm/gc-ergonomics.html
    1. On server-class machines running the server VM, the garbage collector (GC) has changed from the previous serial collector (-XX:+UseSerialGC) to a parallel collector (-XX:+UseParallelGC). You can override this default by using the -XX:+UseSerialGC command-line option to the java command.

    2. On server-class machines running either VM (client or server) with the parallel garbage collector (-XX:+UseParallelGC) the initial heap size and maximum heap size have changed as follows.
      initial heap size:

      Larger of 1/64th of the machine's physical memory on the machine or some reasonable minimum. Before J2SE 5.0, the default initial heap size was a reasonable minimum, which varies by platform. You can override this default using the -Xms command-line option.

      maximum heap size:

      Smaller of 1/4th of the physical memory or 1GB. Before J2SE 5.0, the default maximum heap size was 64MB. You can override this default using the -Xmx command-line option.

    'java core' 카테고리의 다른 글

    자바 소스 설치하기  (0) 2010.10.01
    java checked Exception에 대한 고찰  (0) 2010.10.01
    java -server  (0) 2010.08.19
    G1 알고리즘 공부  (0) 2010.08.09
    JDK 1.6.0 update 21 때문에 Eclipse 문제 발생  (0) 2010.08.09
    Posted by '김용환'
    ,

    java -server

    java core 2010. 8. 19. 16:06

    jdk1.5 부터는 메모리 2G이상, cpu 2개이상 있으면, 자동으로 server-class로 판별하고 자동으로 -server로 jvm을 실행하게 된다.

    리눅스 서버는 대부분이 cpu2개이상, 메모리 2G이상이면, -server 옵션 안써도 됨~

     

     

    http://java.sun.com/docs/hotspot/gc5.0/ergo5.html

     

    In the J2SE platform version 5.0 a class of machine referred to as a server-class machine has been defined as a machine with

    - 2 or more physical processors

    - 2 or more Gbytes of physical memory

     

    On server-class machines by default the following are selected.

    - Throughput garbage collector

    - Heap sizes

    - initial heap size of 1/64 of physical memory up to 1Gbyte

    - maximum heap size of ¼ of physical memory up to 1Gbyte

    - Server runtime compiler

    'java core' 카테고리의 다른 글

    java checked Exception에 대한 고찰  (0) 2010.10.01
    Java option 관련  (0) 2010.08.31
    G1 알고리즘 공부  (0) 2010.08.09
    JDK 1.6.0 update 21 때문에 Eclipse 문제 발생  (0) 2010.08.09
    Random과 SecureRandom의 차이  (0) 2010.08.05
    Posted by '김용환'
    ,