JVM (2)

💻 Programming/Java

JVM 클래스로더란? ( What is ClassLoader ? )

1. 개요
Cass Loader 란 abstrace class로써 Bytecode를 읽어 들여서 class 객체를 생성하는
역활을 담당한다.

Class Loader가 Class를 Loading하는 시점은 ComplieTime이 아닌 Run Time에 Loading이 된다.

프로그래머 가 SampleTest aaa = new SampleTest(); 라는 코드를 처음 실행하면
JVM은 SampleTest라는 Class를 Class Loader를 통해서 SampleTest.clas의 ByteCode를
최초로 메모리에 Load하게 된다. 



2. ClassLoader 기술적 특징
   - Hierarchical 
     Class Loader는 Hierarchical 하게 생성이 가능하고, Parent class laoder에서, child class loader
     갖는것과 같이 Class Loader간의 계층형 구조를 갖게 된다. 최상위 Class Loader는  
     "bootstrap"   Class Loader가 위치 하게 된다.

   - Delegate load request
      Class loading에는 일정한 규칙이 필요하다. 이는 Class Loader가 계측형의 구조를 가지고
      있기 때문에, 어느 시점에 Class 로딩 요청을 받으면 상위 Class Loader가 Loding한 Class가 
      우선권을 가진다. 

   - Have visibility constraint
     Child Class Loader는 Parent Class Loader의 Clss를 찾을수 있지만, 그 반대의 경우는 불가능하다.

   - Cannot unload classes
      Class Loader에 의해서 Loading된 Class들은 unload 될수가 없다.



3. Class Loader 위임
   -

옆의 그림은 class loader delegation model 이다.
     이는 Loading요청을 서로 에게
     전달 하는 ClassLoader의 그래프
     이다. 

     옆의 그림과 같이 Class Loader
     들은 하나의 delegation parent
     함께생성되고 다음 위치 에서
     Class를 찾는다.

     * 다음 위치란
      Cache, Parent, Self

    CalssLoader가 최초 하는 일은
    전에도 같은 Class를 Loading
    하도록 요청을 받았는지를
    먼저 파악한다.

    만약 요청을 받은적이 있으면,
    Cache에 저장된 Class를
    리턴 한다.

    그렇지 않을 경우,
    Parent Class를 Loading 할
    기회를 준다.

    이러한 두 단계들이 반복되고 Depth First 방식으로 탐색이 진행 된다.

    만약 Parent Class에도 해당 Class가 존재하지 않으면 (ClassNotFoundException)
    ClassLoader는 Class의 소스에 대한 공유(작업한 코드)의 경로 (Self)를 검색한다.

    Parent ClassLoader는 Class를 처음으로 loading할 기회가 주어지기 때문에 Root에
    가장 가까운 ClassLoader에 의해 로딩 된다.

   가장 핵심적인 bootstrap class들은 java.lang.Object같은 정확한 클래스 버전이 로딩되었는지
   확인하고, Class Loader가 그 자체 또는 부모(Parent)에 의해서 Loading 되었는지
   Class가 불 수 있도록 한다. 위에서 말했다 싶이 자식에 의해 Loading된 Class 들은 볼 수 없다. 


   - Bootstrap Class Loader
   다른 ClassLoader들과는 달리 Bootstrap Class Loader 는 자바 코드에 의해서
   instance화 될 수 없다
   Bootstrap ClassLoader 는 Boot ClassPath에서 핵심 시스템 Class들을 로딩하는데
   이것은 일반적으로 JavaHome의 jre/lib 디렉토리에 있는 JAR 파일들이다.
   단 -Xbootclasspath 옵션으로 classpath를 추가 수정할 수 있다.


   - Extension Class Loader
   주로 jre/lib/ext 디렉토리에 위치한 Extension 디렉토리에서 Class 들을 Loading 한다. 
   사용자의 classpath를 수정하지 않고 다양한 보안 확장 같은 새로운 확자으로 쉽게
   갈 수 있는 기능을 제공 한다.

   - System Class Loader 
   CLASSPATH 환경 변수에 지정된 결로에서 코드를 로딩 한다. 
   기본적으로 이 Class Loader는 사용자가 생성한 모든 ClassLoader의 Parent 이다. 


  
4. Class Loding 단계 
   - Class Loadig은 Loading, Linking, initialzing 단계로 나누어 진다.

   - 대부분의 Class Loading과 관련된 문제는 이 세단계 중 한 단계에서 발생한다.

   - 로딩 단계는 필요한 Class File을 배치하고 ByteCode로 Loading하는 단계 이다.

   - JVM의 로딩 프로세스는 Class 객체에 매우 기본적인 메모리 구조를 제공한다.
     메소드, 필드, 기타 참조 Class 들이 이 단계에서는 다루어지지 않는다.

 
   - Linking은 세 단계 중에서 가장 복잡한 단계이다. 다름과 같이 세 개의 주요 단계들로 나뉜다. 
     ㄱ. ByteCode 확인 - ByteCode가 정상적으로 작동 하는지 확인 한다. 
     ㄴ. Class Preparation - Class 에서 정의된 필드, 메소드, 인터페잇 들을 나타내는 
                                       데이터 구조를 준비한다. 
     ㄷ. Resolving - Class 에 다양한 방식으로 참조된 모든 Class들을 Loading한다. 
                         - super class, interface, fild, method signature, local fild

   - initialize 단계 동안, Class 내에 포함된 정적 initializer들이 실행된다. 이 단계의 끝에 가서는 
     기본 값으로 초기화 된다. 

   - 이 세 단계를 지나면 Class는 완전히 로딩되고 사용할 준비가 된다. 
     Class Loading은 Lazy방식으로 수행 될 수 있기 때문에 일부 Class Loading Processor 는 
     Loading 시점외에 처음 클래스를 사용할 때 수행될 수도 있다.   


5. Explicit Loading vs Implicit Loading
   - 클래스가 로딩되는 두가지 방식의 차이
   - Explicit : 다음과 같은 메소드 호출들 중 하나를 사용하여 로딩될 때 발생한다.
                  - (java.lang.ClassLoader).loadClass()
                  - Class.forName()
   - 이러한 메소드들 중 하나가 호출 되면 이름이 인자로 지정된 클래스가 클래스 로더에 의해서
     로딩
된다. 
     그렇지 않을 경우, 로더는 클래스를 로딩하기 위해 delegation model을 사용한다.
 
   - Implicit : Class 가 레퍼런스, 인스턴스화, 명시적 메소드 호출을 제외한 상속의 경우 로딩되는 방식
                   경우 슬그머니 로딩작업은 초기화되고 JVM은 필요한 레퍼런스를 결정하여
                   만약 로딩이 되어 있으면 레퍼런스만 리턴되고 그렇지 않을 경우 델리게이션 모델을
                   사용하여 클래스를 로딩하게 된다. 

   


참고 자료:
http://www.ibm.com/developerworks/java/library/j-dclp1/index.html?S_TACT=105AGX02&S_CMP=EDU
및 인터넷 문서



출처 : http://liebus.tistory.com/30



출처 : http://docs.oracle.com/javase/7/docs/technotes/tools/share/jstat.html

 

SYNOPSIS

jstat [ generalOption | outputOptions vmid [interval[s|ms] [count]] ]

PARAMETERS

generalOption
A single general command-line option (-help or -options)
outputOptions
One or more output options, consisting of a single statOption, plus any of the -t, -h, and -J options.
vmid
Virtual machine identifier, a string indicating the target Java virtual machine (JVM). The general syntax is
[protocol:][//]lvmid[@hostname[:port]/servername]
The syntax of the vmid string largely corresponds to the syntax of a URI. The vmid can vary from a simple integer representing a local JVM to a more complex construction specifying a communications protocol, port number, and other implementation-specific values. See Virtual Machine Identifier for details.
interval[s|ms]
Sampling interval in the specified units, seconds (s) or milliseconds (ms). Default units are milliseconds. Must be a positive integer. If specified, jstat will produce its output at each interval.
count
Number of samples to display. Default value is infinity; that is, jstat displays statistics until the target JVM terminates or the jstat command is terminated. Must be a positive integer.

DESCRIPTION

The jstat tool displays performance statistics for an instrumented HotSpot Java virtual machine (JVM). The target JVM is identified by its virtual machine identifier, or vmid option described below.

NOTE: This utility is unsupported and may not be available in future versions of the JDK. It is not currently available on Windows 98 and Windows ME. platforms. 

VIRTUAL MACHINE IDENTIFIER

The syntax of the vmid string largely corresponds to the syntax of a URI:

[protocol:][//]lvmid[@hostname][:port][/servername]
protocol
The communications protocol. If the protocol is omitted and a hostname is not specified, the default protocol is a platform specific optimized local protocol. If the protocol is omitted and a hostname is specified, then the default protocol is rmi.
lvmid
The local virtual machine identifier for the target JVM. The lvmid is a platform-specific value that uniquely identifies a JVM on a system. The lvmid is the only required component of a virtual machine identifier. The lvmid is typically, but not necessarily, the operating system's process identifier for the target JVM process. You can use the jps command to determine the lvmid. Also, you can determine lvmid on Unix platforms with the ps command, and on Windows with the Windows Task Manager.
hostname
A hostname or IP address indicating the target host. If hostname is omitted, then the target host is the local host.
port
The default port for communicating with the remote server. If the hostname is omitted or the protocol specifies an optimized, local protocol, then port is ignored. Otherwise, treatment of the port parameter is implementation specific. For the default rmi protocol, the port indicates the port number for the rmiregistry on the remote host. If port is omitted, and protocol indicates rmi, then the default rmiregistry port (1099) is used.
servername
The treatment of this parameter depends on implementation. For the optimized local protocol, this field is ignored. For the rmi protocol, it represents the name of the RMI remote object on the remote host.

OPTIONS

The jstat command supports two types of options, general options and output options. General options cause jstat to display simple usage and version information. Output options determine the content and format of the statistical output. 

NOTE: All options, and their functionality are subject to change or removal in future releases.

GENERAL OPTIONS

If you specify one of the general options, you cannot specify any other option or parameter.

-help
Display help message.
-options
Display list of statistics options. See the Output Options section below.

OUTPUT OPTIONS

If you do not specify a general option, then you can specify output options. Output options determine the content and format of jstat's output, and consist of a single statOption, plus any of the other output options (-h, -t, and -J). The statOption must come first.

Output is formatted as a table, with columns are separated by spaces. A header row with titles describes the columns. Use the -h option to set the frequency at which the header is displayed. Column header names are generally consistent between the different options. In general, if two options provide a column with the same name, then the data source for the two columns are the same.

Use the -t option to display a time stamp column, labeled Timestamp as the first column of output. The Timestamp column contains the elapsed time, in seconds, since startup of the target JVM. The resolution of the time stamp is dependent on various factors and is subject to variation due to delayed thread scheduling on heavily loaded systems.

Use the interval and count parameters to determine how frequently and how many times, respectively, jstat displays its output.

NOTE: You are advised not to write scripts to parse jstat's output since the format may change in future releases. If you choose to write scripts that parse jstat output, expect to modify them for future releases of this tool.

-statOption
Determines the statistics information that jstat displays. The following table lists the available options. Use the -options general option to display the list of options for a particular platform installation.

OptionDisplays...
classStatistics on the behavior of the class loader.
compilerStatistics of the behavior of the HotSpot Just-in-Time compiler.
gcStatistics of the behavior of the garbage collected heap.
gccapacityStatistics of the capacities of the generations and their corresponding spaces.
gccauseSummary of garbage collection statistics (same as -gcutil), with the cause of the last and current (if applicable) garbage collection events.
gcnewStatistics of the behavior of the new generation.
gcnewcapacityStatistics of the sizes of the new generations and its corresponding spaces.
gcoldStatistics of the behavior of the old and permanent generations.
gcoldcapacityStatistics of the sizes of the old generation.
gcpermcapacityStatistics of the sizes of the permanent generation.
gcutilSummary of garbage collection statistics.
printcompilationHotSpot compilation method statistics.
-h n
Display a column header every n samples (output rows), where n is a positive integer. Default value is 0, which displays the column header above the first row of data.
-t
Display a timestamp column as the first column of output. The timestamp is the time since the start time of the target JVM.
-JjavaOption
Pass javaOption to the java application launcher. For example, -J-Xms48m sets the startup memory to 48 megabytes. For a complete list of options, see java - the Java application launcher

STATOPTIONS AND OUTPUT

The following tables summarize the columns that jstat outputs for each statOption

-class Option

Class Loader Statistics
ColumnDescription
LoadedNumber of classes loaded.
BytesNumber of Kbytes loaded.
UnloadedNumber of classes unloaded.
BytesNumber of Kbytes unloaded.
TimeTime spent performing class load and unload operations.

-compiler Option

HotSpot Just-In-Time Compiler Statistics
ColumnDescription
CompiledNumber of compilation tasks performed.
FailedNumber of compilation tasks that failed.
InvalidNumber of compilation tasks that were invalidated.
TimeTime spent performing compilation tasks.
FailedTypeCompile type of the last failed compilation.
FailedMethodClass name and method for the last failed compilation.

-gc Option

Garbage-collected heap statistics
ColumnDescription
S0CCurrent survivor space 0 capacity (KB).
S1CCurrent survivor space 1 capacity (KB).
S0USurvivor space 0 utilization (KB).
S1USurvivor space 1 utilization (KB).
ECCurrent eden space capacity (KB).
EUEden space utilization (KB).
OCCurrent old space capacity (KB).
OUOld space utilization (KB).
PCCurrent permanent space capacity (KB).
PUPermanent space utilization (KB).
YGCNumber of young generation GC Events.
YGCTYoung generation garbage collection time.
FGCNumber of full GC events.
FGCTFull garbage collection time.
GCTTotal garbage collection time.

-gccapacity Option

Memory Pool Generation and Space Capacities
ColumnDescription
NGCMNMinimum new generation capacity (KB).
NGCMXMaximum new generation capacity (KB).
NGCCurrent new generation capacity (KB).
S0CCurrent survivor space 0 capacity (KB).
S1CCurrent survivor space 1 capacity (KB).
ECCurrent eden space capacity (KB).
OGCMNMinimum old generation capacity (KB).
OGCMXMaximum old generation capacity (KB).
OGCCurrent old generation capacity (KB).
OCCurrent old space capacity (KB).
PGCMNMinimum permanent generation capacity (KB).
PGCMXMaximum Permanent generation capacity (KB).
PGCCurrent Permanent generation capacity (KB).
PCCurrent Permanent space capacity (KB).
YGCNumber of Young generation GC Events.
FGCNumber of Full GC Events.

-gccause Option

This option displays the same summary of garbage collection statistics as the -gcutil option, but includes the causes of the last garbage collection event and (if applicable) the current garbage collection event. In addition to the columns listed for -gcutil, this option adds the following columns:

Garbage Collection Statistics, Including GC Events
ColumnDescription
LGCCCause of last Garbage Collection.
GCCCause of current Garbage Collection.

-gcnew Option

New Generation Statistics
ColumnDescription
S0CCurrent survivor space 0 capacity (KB).
S1CCurrent survivor space 1 capacity (KB).
S0USurvivor space 0 utilization (KB).
S1USurvivor space 1 utilization (KB).
TTTenuring threshold.
MTTMaximum tenuring threshold.
DSSDesired survivor size (KB).
ECCurrent eden space capacity (KB).
EUEden space utilization (KB).
YGCNumber of young generation GC events.
YGCTYoung generation garbage collection time.

-gcnewcapacity Option

New Generation Space Size Statistics
ColumnDescription
NGCMN
Minimum new generation capacity (KB).
NGCMX Maximum new generation capacity (KB).
NGC Current new generation capacity (KB).
S0CMXMaximum survivor space 0 capacity (KB).
S0CCurrent survivor space 0 capacity (KB).
S1CMXMaximum survivor space 1 capacity (KB).
S1CCurrent survivor space 1 capacity (KB).
ECMXMaximum eden space capacity (KB).
ECCurrent eden space capacity (KB).
YGCNumber of young generation GC events.
FGCNumber of Full GC Events.

-gcold Option

Old and Permanent Generation Statistics
ColumnDescription
PCCurrent permanent space capacity (KB).
PUPermanent space utilization (KB).
OCCurrent old space capacity (KB).
OUold space utilization (KB).
YGCNumber of young generation GC events.
FGCNumber of full GC events.
FGCTFull garbage collection time.
GCTTotal garbage collection time.

-gcoldcapacity Option

Old Generation Statistics
ColumnDescription
OGCMNMinimum old generation capacity (KB).
OGCMXMaximum old generation capacity (KB).
OGCCurrent old generation capacity (KB).
OCCurrent old space capacity (KB).
YGCNumber of young generation GC events.
FGCNumber of full GC events.
FGCTFull garbage collection time.
GCTTotal garbage collection time.

-gcpermcapacity Option

Permanent Generation Statistics
ColumnDescription
PGCMNMinimum permanent generation capacity (KB).
PGCMXMaximum permanent generation capacity (KB).
PGCCurrent permanent generation capacity (KB).
PCCurrent permanent space capacity (KB).
YGCNumber of young generation GC events.
FGCNumber of full GC events.
FGCTFull garbage collection time.
GCTTotal garbage collection time.

-gcutil Option

Summary of Garbage Collection Statistics
ColumnDescription
S0Survivor space 0 utilization as a percentage of the space's current capacity.
S1Survivor space 1 utilization as a percentage of the space's current capacity.
EEden space utilization as a percentage of the space's current capacity.
OOld space utilization as a percentage of the space's current capacity.
PPermanent space utilization as a percentage of the space's current capacity.
YGCNumber of young generation GC events.
YGCTYoung generation garbage collection time.
FGCNumber of full GC events.
FGCTFull garbage collection time.
GCTTotal garbage collection time.

-printcompilation Option

HotSpot Compiler Method Statistics
ColumnDescription
CompiledNumber of compilation tasks performed by the most recently compiled method.
SizeNumber of bytes of bytecode of the most recently compiled method.
TypeCompilation type of the most recently compiled method.
MethodClass name and method name identifying the most recently compiled method. Class name uses "/" instead of "." as namespace separator. Method name is the method within the given class. The format for these two fields is consistent with the HotSpot - XX:+PrintComplation option.

EXAMPLES

This section presents some examples of monitoring a local JVM with a lvmid of 21891.

Using the gcutil option

This example attaches to lvmid 21891 and takes 7 samples at 250 millisecond intervals and displays the output as specified by the -gcutil option.

jstat -gcutil 21891 250 7
S0 S1 E O P YGC YGCT FGC FGCT GCT
12.44 0.00 27.20 9.49 96.70 78 0.176 5 0.495 0.672
12.44 0.00 62.16 9.49 96.70 78 0.176 5 0.495 0.672
12.44 0.00 83.97 9.49 96.70 78 0.176 5 0.495 0.672
0.00 7.74 0.00 9.51 96.70 79 0.177 5 0.495 0.673
0.00 7.74 23.37 9.51 96.70 79 0.177 5 0.495 0.673
0.00 7.74 43.82 9.51 96.70 79 0.177 5 0.495 0.673
0.00 7.74 58.11 9.51 96.71 79 0.177 5 0.495 0.673

The output of this example shows that a young generation collection occurred between the 3rd and 4th sample. The collection took 0.001 seconds and promoted objects from the eden space (E) to the old space (O), resulting in an increase of old space utilization from 9.49% to 9.51%. Before the collection, the survivor space was 12.44% utilized, but after this collection it is only 7.74% utilized.

Repeating the column header string

This example attaches to lvmid 21891 and takes samples at 250 millisecond intervals and displays the output as specified by -gcutil option. In addition, it uses the -h3 option to output the column header after every 3 lines of data.

jstat -gcnew -h3 21891 250
S0C S1C S0U S1U TT MTT DSS EC EU YGC YGCT
64.0 64.0 0.0 31.7 31 31 32.0 512.0 178.6 249 0.203
64.0 64.0 0.0 31.7 31 31 32.0 512.0 355.5 249 0.203
64.0 64.0 35.4 0.0 2 31 32.0 512.0 21.9 250 0.204
S0C S1C S0U S1U TT MTT DSS EC EU YGC YGCT
64.0 64.0 35.4 0.0 2 31 32.0 512.0 245.9 250 0.204
64.0 64.0 35.4 0.0 2 31 32.0 512.0 421.1 250 0.204
64.0 64.0 0.0 19.0 31 31 32.0 512.0 84.4 251 0.204
S0C S1C S0U S1U TT MTT DSS EC EU YGC YGCT
64.0 64.0 0.0 19.0 31 31 32.0 512.0 306.7 251 0.204

In addition to showing the repeating header string, this example shows that between the 2nd and 3rd samples, a young GC occurred. Its duration was 0.001 seconds. The collection found enough live data that the survivor space 0 utilization (S0U) would would have exceeded the desired survivor Size (DSS). As a result, objects were promoted to the old generation (not visible in this output), and the tenuring threshold (TT) was lowered from 31 to 2.

Another collection occurs between the 5th and 6th samples. This collection found very few survivors and returned the tenuring threshold to 31.

Including a time stamp for each sample

This example attaches to lvmid 21891 and takes 3 samples at 250 millisecond intervals. The -t option is used to generate a time stamp for each sample in the first column.

jstat -gcoldcapacity -t 21891 250 3
Timestamp OGCMN OGCMX OGC OC YGC FGC FGCT GCT
150.1 1408.0 60544.0 11696.0 11696.0 194 80 2.874 3.799
150.4 1408.0 60544.0 13820.0 13820.0 194 81 2.938 3.863
150.7 1408.0 60544.0 13820.0 13820.0 194 81 2.938 3.863

The Timestamp column reports the elapsed time in seconds since the start of the target JVM. In addition, the -gcoldcapacity output shows the old generation capacity (OGC) and the old space capacity (OC) increasing as the heap expands to meet allocation and/or promotion demands. The old generation capacity (OGC) has grown to from 11696 KB to 13820 KB after the 81st Full GC (FGC). The maximum capacity of the generation (and space) is 60544 KB (OGCMX), so it still has room to expand.

Monitor instrumentation for a remote JVM

This example attaches to lvmid 40496 on the system named remote.domain using the -gcutil option, with samples taken every second indefinitely.

jstat -gcutil 40496@remote.domain 1000
... output omitted

The lvmid is combined with the name of the remote host to construct a vmid of 40496@remote.domain. This vmid results in the use of the rmi protocol to communicate to the default jstatd server on the remote host. The jstatd server is located using the rmiregistry on remote.domain that is bound to the default rmiregistry port (port 1099).

SEE ALSO

  • java - the Java Application Launcher
  • jps - the Java Process Status Application
  • jstatd - the jvmstat daemon
  • rmiregistry - the Java Remote Object Registry