StringWriter sw = new StringWriter();
      e.printStackTrace(new PrintWriter(sw));
      String stacktrace = sw.toString();
      System.out.println("stacktrace = " + stacktrace.split("\n")[0]);

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

-XX:+AggressiveOpts -XX:+DoEscapeAnalysis 테스트  (0) 2010.03.02
JVM crash..  (0) 2010.02.25
/tmp/hsperfdata_계정(hsperfdata_www)/asdfjasdfd 파일  (0) 2010.02.22
Java Dns Cache관련  (0) 2010.01.11
JMX Test Code  (0) 2009.12.31
Posted by '김용환'
,


자바는 기본적으로 /tmp/hsperfdata_계정 디렉토리 밑에 코어 파일을 생성한다.
코어 덤프인 것 같은데..(구글링 참조)
http://stackoverflow.com/questions/76327/how-can-i-prevent-java-from-creating-hsperfdata-files


 /tmp/hsperfdata_www/1231 파일이 존재한다.

이 파일은 자바가 종료되거나 Critical Error 발생시 자바의 코어 파일이 덤프된다.

이 파일이 안오게 하려면,  jvm 옵션을 추가해야 한다.

-XX:-UsePerfData


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

JVM crash..  (0) 2010.02.25
Exception 이름과 실제 내용만 찍기  (0) 2010.02.25
Java Dns Cache관련  (0) 2010.01.11
JMX Test Code  (0) 2009.12.31
Studing JVM this week  (0) 2009.12.11
Posted by '김용환'
,

Java Dns Cache관련

java core 2010. 1. 11. 10:30



java 디폴트로 java의 security 설정은 DNS 정보에 대해 영구적인 캐시를 하기 때문에 별도 설정하지 않는다면,  tomcat 은 DNS에서 lookup이 되는 동안에는 IP 정보를 갱신하지 않는다.

DNS가 중간에 바뀌면, 모니터링 서버를 리스타트하는 경우가 많았는데, 이럴 필요가 없다.

<설정 변경>
1. 설정 변경 파일
$JAVA_HOME/jre/lib/security/java.security

2. 설정 추가 라인(TTL 5분)
networkaddress.cache.ttl=300

3. 톰캣 Restart

<톰캣 웹 App>

java.security.Security.setProperty("networkaddress.cache.ttl" , "300");






* NSCD (DNS 캐쉬 데몬)
만약 시스템에서 nscd를 (/usr/sbin/nscd - name service cache daemon) 사용중이면,
    Reference : http://linux.die.net/man/8/nscd
/etc/nscd.conf 파일의 설정을 변경하고 nscd 데몬을 Restart하도록 한다.
nscd 설정 변경(TTL을 5분으로 변경, Default 1시간)
1. nscd.conf 설정
positive-time-to-live   hosts           300

2. nscd 데몬 Restart
service nscd restart




----

이는 과거 버전 java 5 이전 내용이다. java6 부터는 30초가 기본값으로 변경되었다.



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

Exception 이름과 실제 내용만 찍기  (0) 2010.02.25
/tmp/hsperfdata_계정(hsperfdata_www)/asdfjasdfd 파일  (0) 2010.02.22
JMX Test Code  (0) 2009.12.31
Studing JVM this week  (0) 2009.12.11
JDK bug (conncurrent lock??)  (0) 2009.12.11
Posted by '김용환'
,

JMX Test Code

java core 2009. 12. 31. 11:00




import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class AAA {
 public static void main(String[] args) throws Exception {

  String hostName = "aaa.google.com";
  String port = "13221";
  String jmxConnURL = "service:jmx:rmi:///jndi/rmi://" + hostName + ":" + port + "/jmxrmi";
  JMXServiceURL address = new JMXServiceURL(jmxConnURL);
  JMXConnector connector = DataJMXConnector.connectWithTimeout(address, 1000, TimeUnit.SECONDS);
  if (connector == null) {
   throw new IOException("connect failed to url : " + jmxConnURL);
  }
  
  connector.connect(null);
  
  MBeanServerConnection mbsc = connector.getMBeanServerConnection();
  System.out.println(mbsc.getMBeanCount());

 }
 
 
}

class DataJMXConnector {
 private static final ThreadFactory daemonThreadFactory = new DaemonThreadFactory();
 
 public static JMXConnector connectWithTimeout(final JMXServiceURL url, long timeout, TimeUnit unit) throws IOException {
  final BlockingQueue<Object> mailbox = new ArrayBlockingQueue<Object>(1);
  ExecutorService executor = Executors.newSingleThreadExecutor(daemonThreadFactory);
  System.out.println("0");
  executor.submit(new Runnable() {
      public void run() {
    try {
      System.out.println("xx");
        JMXConnector connector = JMXConnectorFactory.connect(url);
        System.out.println("1");
        if (!mailbox.offer(connector)) {
         System.out.println("2");
         connector.close();
        }
    } catch (Throwable t) {
     System.out.println("3");
        mailbox.offer(t);
        t.printStackTrace();
    }
      }
  });
  
  Object result;
  try {
      result = mailbox.poll(timeout, unit);
      if (result == null) {
       if (!mailbox.offer("")) {
        result = mailbox.take();
       }
      }
  } catch (InterruptedException e) {
      throw initCause(new InterruptedIOException(e.getMessage()), e);
  } finally {
      executor.shutdown();
  }
  
  if (result == null) {
      throw new SocketTimeoutException("Connect timed out: " + url);
  } else if (result instanceof JMXConnector) {
      return (JMXConnector) result;
  } else {
   return null;
  }
 }

    private static <T extends Throwable> T initCause(T wrapper, Throwable wrapped) {
  wrapper.initCause(wrapped);
  return wrapper;
    }

    private static class DaemonThreadFactory implements ThreadFactory {
  public Thread newThread(Runnable r) {
      Thread t = Executors.defaultThreadFactory().newThread(r);
      t.setDaemon(true);
      return t;
  }
    }
}

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

/tmp/hsperfdata_계정(hsperfdata_www)/asdfjasdfd 파일  (0) 2010.02.22
Java Dns Cache관련  (0) 2010.01.11
Studing JVM this week  (0) 2009.12.11
JDK bug (conncurrent lock??)  (0) 2009.12.11
Java Garbage Collection, Monitoring and Tuning  (0) 2009.12.09
Posted by '김용환'
,

Studing JVM this week

java core 2009. 12. 11. 22:47

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

Java Dns Cache관련  (0) 2010.01.11
JMX Test Code  (0) 2009.12.31
JDK bug (conncurrent lock??)  (0) 2009.12.11
Java Garbage Collection, Monitoring and Tuning  (0) 2009.12.09
Eclipse(JVM) Crash  (0) 2009.12.09
Posted by '김용환'
,


I use ReentrantLock, but something strange happend. Locked..
(JDK 6 Update 6, Redhat Enterprise 3)

 class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...

   public void m() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }

   public void n() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }

 }
 

Like below, many thread locked by a 0x58266548 .

Many threads locked on the ReentrantLock instance.. So.. My clusion is "removing ReentrantLock instance" in my code. There are bug reports related with ReentrantLock in bug.sun.com and web..

I changed "lock" to synchronized..



"Worker-17" prio=10 tid=0x4c504400 nid=0x1179 waiting on condition [0x490be000..0x490beea0]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x58266548> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:747)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireQueued(AbstractQueuedSynchronizer.java:778)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(AbstractQueuedSynchronizer.java:1114)
    at java.util.concurrent.locks.ReentrantLock$NonfairSync.lock(ReentrantLock.java:186)
    at java.util.concurrent.locks.ReentrantLock.lock(ReentrantLock.java:262)
.. my package-source...

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

JMX Test Code  (0) 2009.12.31
Studing JVM this week  (0) 2009.12.11
Java Garbage Collection, Monitoring and Tuning  (0) 2009.12.09
Eclipse(JVM) Crash  (0) 2009.12.09
Cheking JMX Port Alive  (0) 2009.11.19
Posted by '김용환'
,

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

Studing JVM this week  (0) 2009.12.11
JDK bug (conncurrent lock??)  (0) 2009.12.11
Eclipse(JVM) Crash  (0) 2009.12.09
Cheking JMX Port Alive  (0) 2009.11.19
JDK 7 언어적으로 특징적으로 변하는 부분. (api 제외)  (0) 2009.11.13
Posted by '김용환'
,

Eclipse(JVM) Crash

java core 2009. 12. 9. 10:53


After I installed Windows 7, I launched eclipse.
But, Somthing wrong happend.

JVM Crash!!

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x76fe205b, pid=252, tid=424
#
# JRE version: 6.0_17-b04
# Java VM: Java HotSpot(TM) Client VM (14.3-b01 mixed mode, sharing windows-x86 )
# Problematic frame:
# C  [ntdll.dll+0x5205b]
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
#


Why?
I was all day thinking about it. I found it.

I used a eclipse workspace installed on windows xp that is my ex-os on my desktop pc.
I thought new eclipse tried to use the workspace based on windows xp, but failed to use it.
So, JVM was crashed.

I made new eclipse workspace. Never jvm crash happend again.
Posted by '김용환'
,

Cheking JMX Port Alive

java core 2009. 11. 19. 15:03

Cmdline-jmxclient.jar is very useful to check if jmx port of application alive.
You can download from jmxclient. and can use it below examples.
http://crawler.archive.org/cmdline-jmxclient/

When you use this command in shell, if you do not see any kinds of exception, it means successful. But, if you see a exception, it means a problem of application.

Ex1) Application have no jmx port
java -jar cmdline-jmxclient.jar - idowww.svr.google.com:11005 java.lang:type=Memory gc
Exception in thread "main" java.io.IOException: Failed to retrieve RMIServer stub: 
javax.naming.ServiceUnavailableException [Root exception is java.rmi.ConnectException: Connection refused to host: idombr702.svr.hangame.com; nested exception is:
        java.net.ConnectException: Connection refused]
        at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:323)
        at javax.management.remote.JMXConnectorFactory.connect(JMXConnectorFactory.java:248)
        at org.archive.jmx.Client.execute(Client.java:225)
        at org.archive.jmx.Client.main(Client.java:154)


 Ex2) Application have trouble of binding jmx port
java -jar cmdline-jmxclient.jar - idowww.svr.google.com:11005 java.lang:type=Memory gc

Exception in thread "main" java.io.IOException: Failed to retrieve RMIServer stub: javax.naming.NameNotFoundException: jmxrmi
        at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:323)
        at javax.management.remote.JMXConnectorFactory.connect(JMXConnectorFactory.java:248)
        at org.archive.jmx.Client.execute(Client.java:225)
        at org.archive.jmx.Client.main(Client.java:154)
Caused by: javax.naming.NameNotFoundException: jmxrmi
        at com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:99)
        at com.sun.jndi.toolkit.url.GenericURLContext.lookup(GenericURLContext.java:185)
        at javax.naming.InitialContext.lookup(InitialContext.java:392)
        at javax.management.remote.rmi.RMIConnector.findRMIServerJNDI(RMIConnector.java:1871)
        at javax.management.remote.rmi.RMIConnector.findRMIServer(RMIConnector.java:1841)
        at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:257)
        ... 3 more

 Ex2) Success - no print out.
Shell>java -jar cmdline-jmxclient.jar - idombr701.svr.hangame.com:11005 java.lang:type=Memory gc
Shell>
Posted by '김용환'
,

출처
http://weblogs.java.net/blog/forax/archive/2009/08/29/seven-small-languages-changes-will-be-jdk7
http://blogs.sun.com/darcy/entry/project_coin_final_five


he seven small languages changes that will be in JDK7

Posted by forax on August 29, 2009 at 7:08 AM PDT

Joe Darcy has revealed the changes accepted to be included in JDK7 on coin-dev mailing list 
And the final Project Coin changes accepted are:

  1.     Improved Type Inference for Generic Instance Creation (diamond) 
  2.     Simplified Varargs Method Invocation
  3.     Strings in switch
  4.     An omnibus proposal for better integral literals
  5.     Automatic Resource Management
  6.     Language support for JSR 292
  7.     Language support for Collections

I think this set of proposal is coherent. Lot of those proposals was already in the starting blocks:

  • Diamond is already implemented, see my previous blog entry.
  • Simplified varargs is just a matter to add a new warning, so not a big deal.
  • String in switch. A little more complex but not that hard.
  • Better integral literals, the unsigned syntax need to be explored and implementation will be straighforward.
  • ARM block, need to be implemented but the current spec is crystal clear.
  • Language support for JSR292, There is already an implementation available in javac.
    I hope the JSR292 Expert Group will close the last corner cases during the JVM Summit, in two week.

About Language support for collections, hum, I was a complete surprise for me, knowing that Joe said more than one time than only 5 proposal will live in jdk7.
This proposal is a mix of two proposals:

  • Josh Bloch has proposed a syntax pretty clear for collection initialisation and
  • Neal Gafter has proposed a translation scheme to implement indexer.

And in my opinion, there are still lot of work on an unified proposal before its inclusion.
The deadline is short, end of October, I think help of the community is needed so if you want to see a better support for collection in Java,
join us on coin-dev list and help to define/implement this feature.

cheers,
Rémi


1. Improved Type Inference for Generic Instance Creation (Diamond)
List<String> list = new ArrayList<>();

객체 선언을 이렇게 단순시키는 것을 말한다.


2. Simplified Varargs Method Invocation
(출처) http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/000217.html

generic을 추가하면서 너무 타이트하게 waring이 나오는 부분이 있었고, 이런 부분에 대해서 좀 정확치 않은 쪽으로 warning이 나왔는데..
과거

static <T> List<T> asList(T... elements) { ... }

  static List<Callable<String>> stringFactories() {
    Callable<String> a, b, c;
    ...
    *// Warning: **"uses unchecked or unsafe operations"*
    return asList(a, b, c);
  }

=> 실제 메소드가 호출된 곳이 아니라 메소드 선언한 곳에서 warning이 찍히도록 하였다.

  *// Warning: **"enables unsafe generic array creation"*
  static <T> List<T> asList(T... elements) { ... }

  static List<Callable<String>> stringFactories() {
    Callable<String> a, b, c;
    ...
    return asList(a, b, c);
  }

=> 또한 이런 부분에 대해서 generic-varagrs 로 해서 warning이 안나오도록 할 수 있다.
  *@SuppressWarnings("generic-varargs")
  // Ensures only values of type T can be stored in elements.
*  static <T> List<T> asList(T... elements) { ... }



3. Strings in Switch
출처 : http://mail.openjdk.java.net/pipermail/coin-dev/2009-February/000001.html

String s = ...
switch(s) {
  case "foo":
    processFoo(s);
    break;
}


4. An omnibus proposal for better integral literals
아직 확정되지는 않았고, 아래 두 proposal중에서 고를 것 같다.
Binary literals and Underscores in numbers.
http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/000929.html


5. Automatic Resource Management
JDK7으로 가면, 훨씬 개발자가 편하게 개발을 할 수 있고, java io/nio 쪽 api를 쓰면서 stream이나 buffer에 대해서 close() 메소드를 강제로 하지 않아도 될 것 같다.
그리고, 아파치 common의 IOUtils 나 try-catch-finally 안써도 된다.
출처 : http://mail.openjdk.java.net/pipermail/coin-dev/2009-February/000011.html

static String readFirstLineFromFile(String path) throws IOException {

        BufferedReader br = new BufferedReader(new FileReader(path));

        try {

            return br.readLine();

        } finally {

            br.close();

        }

    }


=>JDK 7
try-catch 라는 무조건적 문법에서 try 만 쓸수도 있게 java language spec이 변화되었고, 알아서 내부적으로 resource 관리를 할 수 있게 한다.

static String readFirstLineFromFile2(String path) throws IOException {

        try (BufferedReader br = new BufferedReader(new FileReader(path)) {

           return br.readLine();

        }

    }




또한 이런 코드들도...

static void copy(String src, String dest) throws IOException {
        InputStream in = new FileInputStream(src);
        try {
            OutputStream out = new FileOutputStream(dest);
            try {
                byte[] buf = new byte[8 * 1024];
                int n;
                while ((n = in.read(buf)) >= 0)
                    out.write(buf, 0, n);
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    }


=>JDK7에서는..


static void copy(String src, String dest) throws IOException {

        try (InputStream in = new FileInputStream(src);

             OutputStream out = new FileOutputStream(dest)) {

            byte[] buf = new byte[8192];

            int n;

            while ((n = in.read(buf)) >= 0)

                out.write(buf, 0, n);

        }

    }

6. Language support for JSR 292

일종 동적 클래스가 생겨서, Runtime때 자유롭게 쓸 수 있도록 한 클래스입니다.
http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/001131.html


Dynamic x = (any type of expression can go here);
Object  y = x.foo("ABC").bar(42).baz();

제가 예전에 한 것들을 적용시킬 수 있다면..
Ant를 돌릴 때, 특정 변수값으로 수정해서 컴파일을 달리하고 싶을 때, ant 컴파일 타임때 클래스를 만들거나 하는 작업들, 일종의 클립보드같은 것들을 여기다사 쑤셔 넣을 수도 있을 것 같군요.


7. Language support for collections
http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/001193.html
불편했던 입력방법이 바뀐다.


final List<Integer> piDigits =
Collections.unmodifiableList(Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9 ));

JDK7에서는 이렇게 바뀐다.


final List<Integer> piDigits = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9];



8. 기타로는..
Enhanced null handling
기존


public String getPostcode(Person person) {
if (person != null) {
Address address = person.getAddress();
if (address != null) {
return address.getPostcode();
}
}
return null;
}

=> JDK7

public String getPostcode(Person person) {
return person?.getAddress()?.getPostcode();
}



String str = getStringMayBeNull();
str = (str == null ? “” : str);

=>JDK7


String str = getStringMayBeNull() ?: “”;


Improved catch clause
길게 catch 문없이  or 처럼 쓸 수 있다.

try {
return klass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new AssertionError(e);
}


Comparisons for Enums
enum도 비교가 되게~

boolean isRoyalty(Rank r) {
return rank >= Rank.JACK && rank != Rank.ACE;
}


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

Eclipse(JVM) Crash  (0) 2009.12.09
Cheking JMX Port Alive  (0) 2009.11.19
파일 copy 테스트 (nio, inputstream) 테스트 in java  (0) 2009.09.11
Java Memroy Model  (0) 2009.08.06
Java Pattern 활용하기  (0) 2009.07.23
Posted by '김용환'
,