'Java'에 해당되는 글 17건

  1. 2013.01.05 Internals of Java Class Loading
  2. 2011.04.18 Java classpath
  3. 2011.04.10 OnJava.com
  4. 2010.12.02 jstat
  5. 2010.11.22 java.util.concurrent package
  6. 2010.11.17 Java Hotspot VM Option
  7. 2010.11.04 JMX
  8. 2010.06.21 [link] logging
  9. 2010.01.27 [link] java performance tip
  10. 2010.01.05 [link] IBM Diagnosis documentation

http://onjava.com/pub/a/onjava/2005/01/26/classloading.html

Internals of Java Class Loading

by Binildas Christudas
01/26/2005

Class and Data
- class = code, data = state
- 모든 클래스는 java.lang.Class 의 인스턴스 형태로 code를 가진다
- 컴파일러는 class라는 이름의 public static final 필드를 모든 클래스에 삽입한다.
   public static final Class class;
- JVM이 클래스를 한 번 로드하면, 같은 클래스는 다시 로드되지 않는다.
- 여기서 같은 클래스는 fully qualified name (package name + class name)으로 구별된다.
- JVM에서 fully qualified name과 그 클래스를 로드한 ClassLoader를 함께 사용하여 하나의 고유한 클래스를 식별한다.
- 어떤 클래스를 C1, 패키지를 Pg, 클래스로더 인스턴스를 Kl1 이라고 할 때,
- JVM에서 (C1, Pg, Kl1)C1이라는 클래스의 키이다. 
- 즉, (C1, Pg, Kl1)(C1, Pg, Kl2)는 같은 클래스가 아니다.

Class Loaders
- JVM에서 모든 클래스는 어떤 java.lang.ClassLoader의 인스턴스에 의해 로드된다.
- java.lang.Object 와 기본 클래스들은 bootstrap class loader에 의해 로드된다.
- 이 기본 클래스들은 JRE/lib/rt.jar라는 파일로 패키징된다.
- boot class loader는 natively implementation 된다. JVM마다 구현은 다르다.
- 다음과 같이 core java runtime 클래스의 클래스로더를 얻으려고 하면 null을 얻게된다.
  log(java.lang.String.class.getClassLoader());
- java.ext.dirs property로 얻어지는 경로에서 extension 라이브러리를 찾을 수 있다.
- 이 경로의 모든 jar 파일은 ExtClassLoader에 의해 로드된다.
- 개발자 관점에서 가장 중요한 세번째의 클래스로더는 AppClassLoader이다.
- java.class.path property로 얻어지는 경로의 클래스들은 AppClassLoader에 의해 로드된다.
  이곳이 CLASSPATH이다.
- java.lang.Thread는 public ClassLoader getContextClassLoader()를 포함한다.
- 이것은 context class loader를 리턴한다.
- context class loader는 Thread를 생성한 코드에 의해 제공된다.
- Thread에 의해 실행되는 코드가 클래스나 리소스를 로드할 때 사용된다.

How Class Loaders Work
- bootstrap class loader를 제외한 모든 클래스로더는 parent 클래스로더를 갖는다.
- 모든 클래스로더의 타입은 java.lang.ClassLoader이다.
- 모든 클래스로더의 parent 클래스로더는 그 클래스로더를 로드한 클래스로더이다.
- 클래스로더의 loadClass() 메서드를 사용하여 클래스로더에게 클래스를 요청한다.
- loadClass() 메서드 내부동작은 다음과 같다. (from java.lang.ClassLoader 의 소스코드)

protected synchronized Class<?> loadClass
    (String name, boolean resolve)
    throws ClassNotFoundException{

    // First check if the class is already loaded
    Class c = findLoadedClass(name);
    if (c == null) {
        try {
            if (parent != null) {
                c = parent.loadClass(name, false);
            } else {
                c = findBootstrapClass0(name);
            }
        } catch (ClassNotFoundException e) {
            // If still not found, then invoke
            // findClass to find the class.
            c = findClass(name);
        }
    }
    if (resolve) {
    resolveClass(c);
    }
    return c;


- 클래스로더는 이미 로드된 클래스를 찾을 수 없을 때, parent에게 물어본다.
- parent의 parent (...) 에서도 찾지 못하고 결국 findBootstrapClass0() 역시 실패하면 findClass() 메서드를 호출한다.
- findClass() 메서드의 디폴트 구현은 ClassNotFoundException을 던지는 것이다.

    protected Class<?> findClass(String name)
        throws ClassNotFoundException {
        throw new ClassNotFoundException(name);
    } 


- 커스텀 클래스로더를 구현하는 개발자는 이 메서드를 구현하게 된다.
- findClass() 의 내부에서 클래스로더는 임의의 소스로부터 바이트코드를 얻어온다.
- 여기서 임의의 소스는 filesystem, network URL, database, 혹은 다른 어플리케이션일 수 있다.
- 바이트코드를 얻은 후에 findClass() 메서드는 defineClass() 메서드를 호출해야 한다. (바이트코드를 Class로 변환)
- 자바 런타임은 어떤 클래스로더 인스턴스가 defineClass()를 호출했는지를 구별한다.
- 두 개의 클래스로더 인스턴스가 같은 소스의 바이트코드를 define 하더라도, 두 개의 클래스는 다른 클래스이다.

The Java language specification gives a detailed explanation on the process of loading, linking, and the initialization of classes and interfaces in the Java Execution Engine.

- Figure 1


- 다른 클래스로더에서 로드된 (같은 바이트코드의) 클래스를 대입하려고 하는 경우 ClassCastException이 발생한다.

A more detailed explanation on the process of class loading, defining, and linking is in Andreas Schaefer's article "Inside Class Loaders."


Why Do We Need our Own Class Loaders?

Posted by 天下太平
,

Java classpath

Java 2011. 4. 18. 14:13
* Java classpath 설정방법
1. -classpath src1;src2;A.jar;B.jar
2. -cp src1;src2;A.jar;B.jar
3. -Djava.class.path=src1;src2;A.jar;B.jar
4. set CLASSPATH=src1;src2;A.jar;B.jar

* classpath 옵션이 두 개 이상이면
java -cp src1 -cp src2 -cp src3 Test
-> 마지막 옵션 (src3)만 적용된다.

* -cp, -classpath -Djava.class.path 옵션을 섞어서 쓰면
java -Djava.class.path=src1 -cp src2 Test
-> 마지막 옵션 (src2)만 적용된다.

* ClassLoader 종류
- Bootstrap ClassLoader : $JAVA_HOME/jre/lib/rt.jar
- Extension ClassLoader : $JAVA_HOME/jre/lib/ext/*.jar
- Application ClassLoader : $CLASSPATH

* 상위 ClassLoader에 있는 Class가 우선순위가 높다

* ClassLoader C1에서 로드된 클래스 A가 참조하는 클래스 B는 반드시 ClassLoader C1 혹은 C1보다 상위의 ClassLoader에서 찾을 수 있어야 한다.


 
Posted by 天下太平
,

OnJava.com

Java 2011. 4. 10. 22:13
Posted by 天下太平
,

jstat

Java 2010. 12. 2. 10:42
# jstat -help
Usage: jstat -help|-options
       jstat -<option> [-t] [-h<lines>] <vmid> [<interval> [<count>]]

Definitions:
  <option>      An option reported by the -options option
  <vmid>        Virtual Machine Identifier. A vmid takes the following form:
                     <lvmid>[@<hostname>[:<port>]]
                Where <lvmid> is the local vm identifier for the target
                Java virtual machine, typically a process id; <hostname> is
                the name of the host running the target Java virtual machine;
                and <port> is the port number for the rmiregistry on the
                target host. See the jvmstat documentation for a more complete
                description of the Virtual Machine Identifier.
  <lines>       Number of samples between header lines.
  <interval>    Sampling interval. The following forms are allowed:
                    <n>["ms"|"s"]
                Where <n> is an integer and the suffix specifies the units as
                milliseconds("ms") or seconds("s"). The default units are "ms".
  <count>       Number of samples to take before terminating.
  -J<flag>      Pass <flag> directly to the runtime system.
#
# jstat -options
-class
-compiler
-gc
-gccapacity
-gccause
-gcnew
-gcnewcapacity
-gcold
-gcoldcapacity
-gcpermcapacity
-gcutil
-printcompilation

# jstat -gcutil <PID> 1000
 

 
Posted by 天下太平
,

java.util.concurrent package

Java 2010. 11. 22. 13:49
Doug Lea
http://g.oswego.edu/

5 things you didn't know about... java.util.concurrent
http://www.ibm.com/developerworks/java/library/j-5things4.html
http://www.ibm.com/developerworks/java/library/j-5things5.html

5 things you didn't know about... java.util.concurrent (한글)
https://www.ibm.com/developerworks/kr/library/j-5things4.html
http://www.ibm.com/developerworks/kr/library/j-5things5.html

 Part 1.
* TimeUnit : 시간 단위, TimeUnit.SECOND, TimeUnit.MILLISECOND
* CopyOnWriteArrayList : read often, write rarely
* BlockingQueue : queue.take() method 호출했을 때, Queue가 비어있으면 계속 기다린다
* ConcurrentMap : ConcurrentHashMap
* SynchronousQueues : BlockingQueue와 같고, 기다리는 consumner가 있어야만, producer가 insert할 수 있다

Part 2.
* Semaphore : new Semaphore(3), sem.acquire(), sem.release()
* CountDownLatch : new CountDownLatch(5), start.await(), start.countDown()
* Executor, ExecutorService, ScheduledExecutorService : run Runnable or Callable, No fussing with Thread.




자바캔 Java Concurrency : Executor & Callable/Future
http://javacan.tistory.com/entry/134

Java Tutorial - Lesson: Concurrency
http://download.oracle.com/javase/tutorial/essential/concurrency/

Concurrent Programming with J2SE 5.0
http://java.sun.com/developer/technicalArticles/J2SE/concurrency/


 Overview of Concurrency Utilities
Task scheduling framework : Executor
Concurrent collections
Atomic variables
Synchronizers : semaphore, mutex, barrier, latch, exchanger
Locks : limitation of built-in monitor, synchronized
Nanosecond-granurity
java.util.concurrent package
Semaphore : A classic concurrency tool
CyclicBarrier : A resettable multiway synchronization point
CountDownLatch : A utility for blocking until a given number of signals, events, or conditions hold.
Exchanger : Allows two thread to exchange objects at a rendezvous point, and can be useful in pipeline designs.
java.util.concurrent.locks
AtomicInteger number = new AtomicInteger(); number.getAndIncrement();






Posted by 天下太平
,

Java Hotspot VM Option

Java 2010. 11. 17. 18:16
Posted by 天下太平
,

JMX

Java 2010. 11. 4. 17:24
Java Management Extensions (JMX) Technology
http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/

Java Management Extensions (JMX)
http://download.oracle.com/javase/1.5.0/docs/guide/jmx/index.html


Getting started with JMX
http://java.sun.com/developer/technicalArticles/J2SE/jmx.html 


Monitoring and Management using JMX
http://download.oracle.com/javase/1.5.0/docs/guide/management/agent.html

-Dcom.sun.management.jmxremte
-Dcom.sun.management.jmxremote.port=portNumber


An object name consists of two parts, the domain and the key properties.
The domain is a string of characters not including the character colon (:).

An ObjectName can be written as a String with the following elements in order:
  • The domain.
  • A colon (:).
  • A key property list as defined below.

A key property list written as a String is a comma-separated list of elements. Each element is either an asterisk or a key property. A key property consists of a key, an equals (=), and the associated value.



Posted by 天下太平
,

[link] logging

Java 2010. 6. 21. 14:56
Log4J 1.2 Manual
http://logging.apache.org/log4j/1.2/manual.html

Log4j delivers control over logging
http://www.javaworld.com/jw-11-2000/jw-1122-log4j.html

log4j wiki
http://wiki.apache.org/logging-log4j/

[book] The complete log4j manual
https://www.qos.ch/shop/products/eclm/

Simple Logging Facade for Java
http://www.slf4j.org/

JBoss separating application logs
http://community.jboss.org/wiki/SeparatingApplicationLogs


Log4J

components : Logger Appender Layout
Logger = Category (before version 1.2)
Logger name : "com.foo" is parent of "com.foo.bar"
Root Logger
Level : trace, debug, info, warn, error, fatal
Level Inheritance
The inherited level for a given logger C, is equal to the first non-null level in the logger hierarchy, starting at C and proceeding upwards in the hierarchy towards the root logger.

 
Basic Selection Rule
A log request of level p in a logger with (either assigned or inherited, whichever is appropriate) level q, is enabled if p >= q.


Appenders and Layouts

an output destination is called an appender.
Currently, appenders exist for the console, files, GUI components, remote socket servers, JMS, NT Event Loggers, and remote UNIX Syslog daemons.
Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy

 
Appender Additivity
The output of a log statement of logger C will go to all the appenders in C and its ancestors. This is the meaning of the term "appender additivity".

However, if an ancestor of logger C, say P, has the additivity flag set to false, then C's output will be directed to all the appenders in C and its ancestors upto and including P but not the appenders in any of the ancestors of P.

Loggers have their additivity flag set to true by default.





Posted by 天下太平
,

[link] java performance tip

Java 2010. 1. 27. 15:12

Performance tips for the Java final keyword
http://www.javaperformancetuning.com/tips/final.shtml#REF1

Posted by 天下太平
,
Posted by 天下太平
,