Java’s Architecture - 《Pro_Java_8_Programming_(3rd_edition)》

来源:互联网 发布:mysql 错误日志路径 编辑:程序博客网 时间:2024/05/20 04:48

Java’s Architecture


It’s easy to think of Java as merely the programming language with whichyou develop your applications—writing
source files and compiling them into bytecode. However, Java as a programminglanguage is just one
component of Java, and it’s the underlying architecture that gives Java many ofits advantages, including
platform independence.
The complete Java architecture is actually the combination of four components:
The Java programming language
The Java class file format
The Java APIs
The JVM

 

One feature (andsome would say disadvantage) of bytecode is that it’s not executed directly bythe
processor of the machine on which it’s run. The bytecode program is run throughthe JVM, which interprets
the bytecode, and that’s why Java is referred to as an interpreted language. In reality, Java’sdays of being
a purely interpreted language are long gone, and the current architecture ofmost JVM implementations
is a mixture of interpretation and compilation. Interpretation is a relatively slow process compared to
compilation, and it was during the days of purely interpreted Java that itgained a reputation for being slower
than other languages. However, the newer interpreted/compiled hybrid model haslargely eliminated the
speed difference in Java programs and those of other programming languages,making it appropriate for all
but the most resource-intensive applications.

The JVM As aRuntime Execution Environment
Every time you run a Java application, you’re in fact running yourapplication within an instance of the JVM,

and each separate application you run will have its own JVM instance. So far you’ve seen that Java uses an
interpreted form of source code called bytecode, but how do theinstructions you code in the Java programming
language get translated into instructions that the underlying operating system(OS) can understand?
The JVM specification defines an abstract internal architecture for thisprocess. You’ll learn about the
components of this internal architecture in a moment, but at a high level,class files (compiled Java files have
a .class extension and are referred to as class files) are loaded into the JVM where they’rethen executed
by an execution engine. When executing the bytecodes, the JVM interacts withthe underlying OS through
means of native methods, and it’s the implementation of those native methodsthat tie a particular JVM
implementation to a particular platform

 

The Runtime DataAreas of the JVM
Although the individual implementations may differ slightly from platformto platform, every JVM must
supply the runtime components shown in Figure 1-3

 

 

The Heap
The heap is a region of free memory that’s often used for dynamic or temporarymemory allocation. The
heap is the runtime data area that provides memory for class and array objects. When class or array objects
are created in Java, the memory they require is allocated from the heap, whichis created when the JVM
starts. Heap memory is reclaimed when references to an object or array no longer exist by anautomatic
storage management system known as the garbage collection, which you’ll learnmore about later.
The JVM specification doesn’t dictate how the heap is implemented; that’s leftup to the creativity of
the individual implementations of the JVM. The size of the heap may beconstant, or it may be allowed
to grow as needed or shrink if the current size is unnecessarily large. Theprogrammer may be allowed
to specify the initial size of the heap; for example, on the Win32 and Solarisreference implementations,
you can do this with the –mx command-line option. Heap memory doesn’t need to be contiguous. If the
heap runs out of memory and additional memory can’t be allocated to it, thesystem will generate an
OutOfMemoryError exception.

 

The Stack(  注意线程安全方面的知识)
A Java stack frame stores the state of method invocations. The stack framestores data and partial results
and includes the method’s execution environment, any local variables used for the method invocation, and
the method’s operand stack. The operand stack stores the parameters and return values for most bytecode
instructions. The execution environment contains pointers to various aspects ofthe method invocation.





Frames are the components that make up the JVM stack. They store partial results,data, and return
values for methods. They also perform dynamic linking and issue runtimeexceptions. A frame is created
when a method is invoked and destroyed when the method exits for any reason
. A frame consists of an
array of local variables, an operand stack, and a reference to the runtime constant pool of the class of the
current method.
When the JVM runs Java code, only one frame, corresponding to the currentlyexecuting method,
is active at any one time. This is referred to as the current frame. The method it represents is the current
method, and the class that includes that method is the current class. When athread invokes a method
(each thread has its own stack), the JVM creates a new frame,which becomes the current frame, and pushes
it onto the stack for that thread.
As with the heap, the JVM specification leaves it up to the specificimplementation of the JVM how
the stack frames are implemented. The stacks either can be of fixed size or canexpand or contract in size
as needed. The programmer may be given control over the initial size of thestack and its maximum and
minimum sizes. Again, on Win32 and Solaris, this is possible through thecommand-line options –ss and
–oss. If a computation requires a larger stack than is possible, a StackOverflowError exception is generated.

Method Area
The method area is a common storage area shared among all JVM threads. It’s used to storesuch things as
the runtime constant pool, method data, field data, and bytecode for methodsand constructors. The JVM
specification details only the general features of the method area but doesn’tmandate the location of the
area or dictate how the area is implemented. The method area may be a fixedsize, or it may be allowed to
grow or shrink. The programmer may be allowed to specify the initial size ofthe method area, and the area
doesn’t need to be contiguous.


Registers
The registers maintained by the JVM are similar to registers on other computer systems.They reflect the
current state of the machine and are updated as bytecode is executed. Theprimary register is the program
counter (the pc register) that indicates the address of the JVM instructionthat’s currently being executed.
If the method currently being executed is native (written in a language otherthan Java), the value of the
pc register is undefined. Other registers in the JVM include a pointer to theexecution environment of the
current method, a pointer to the first local variable of the currentlyexecuting method, and a pointer to the
top of the operand stack.

 

Runtime Constant Pool
The runtime constant pool is similar to a symbol table used in other programming languages. As thename
suggests, it contains constants including numeric literals and field constants.The memory for each runtime
constant pool is allocated from the method area, and the runtime constant poolis constructed when the
JVM loads the class file for a class or interface.





The JVM:Loading, Linking, and Initializing
For the JVM to interpret a Java bytecode, it must perform three steps forthe required classes and interfaces:
1. Loading: When the JVM loads a class, it finds a binary representation of a class
or interface and creates a Class object from that binary representation (usually
a class file created by a Java compiler). A Class object encapsulates the runtime
state of a class or interface.
2. Linking: Linking is the process of taking the loaded class or interface and
combining it with the runtime of the JVM, preparing it for execution.
3. Initializing: Initialization occurs when the JVM invokes the class or interface
initialization method.
The First Step
The first thing the JVM does when a stand-alone Java application starts iscreate a Class object representing
the Java class that contains the public static void main(String[] args) method. The JVM links and
initializes this class and invokes the main() method, and that method drives the loading, linking, and
initializing of any additional classes and interfaces that are referenced.
Loading
The loading process itself is carried out by a class loader, which is anobject that’s a subclass of ClassLoader;
the class loader will do some of its own verification checks on the class orinterface it’s loading. An
exception is thrown if the binary data representing the compiled class orinterface is malformed, if the
class or interface uses an unsupported version of the class file format, if theclass loader couldn’t find the
definition of the class or interface, or if circularity exists. Class circularity occurs if a class or interface
would be its own superclass.


Two generaltypes of class loader exist: the one supplied by the JVM, which is called the bootstrap
class loader
, and user-defined class loaders.User-defined class loaders are always subclasses of Java’s
ClassLoader class and can be used to create Class objects from nonstandard, user-defined sources. For
instance, the Class object could be extracted from an encrypted file. A loader may delegatepart or all of the
loading process to another loader, but the loader that ultimately creates the Class object is referred to as the
defining loader. The loader thatbegins the loading process is known as the initiating loader.
The loading process using the default bootstrap loader is as follows: Theloader first determines if it has
already been recorded as the initiating loader of a class corresponding to thedesired class file. If it has, the
Class object already exists, and the loader stops. (You should note here thatloading a class isn’t the same as
creating an instance of it; this step merely makes the class available to theJVM.) If it’s not already loaded, the
loader searches for the class file and, if found, will create the Class object from that file. If the class file isn’t
found, a NoClassDefFoundError exception is generated.
When a user-defined class loader is used, the process is somewhat different. Aswith the bootstrap
loader, the user-defined loader first determines if it has already beenrecorded as the initiating loader of a
class file corresponding to the desired class file. If it has, the Class object already exists and the loader stops,
but if it doesn’t already exist, the user-defined loader invokes the loadClass() method. The return value of
that method is the desired class file, and the loadClass() method assembles the array of bytes representing
the class into a ClassFile structure. It then calls the defineClass() method, which creates a Class object
from the ClassFile structure; alternatively, the loadClass() method can simply delegate the loading to
another class loader.


Java Utility Tools: Making the Most of the JVM
Java SE comes with a number of development tools that you can use tocompile, execute, and debug Java
programs; we’ll discuss some of the tools that relate to the JVM in the nextsections. You can find a description
of all the utility tools on the Oracle web site at http://docs.oracle.com/javase/8/docs/technotes/tools/.
The Java Compiler
The compiler that comes with the J2SE is named javac; it reads class and interface definition files and
converts these into bytecode files. The command to run the Java compiler is asfollows:
javac [options] [source files] [@file list]
The options are command-line options. If the number of source files to becompiled is sufficiently short,
the files can just be listed one after another. However, if the number of filesis large, a file containing the
names of the files to be compiled can be used preceded by the @ character.Source code file names must end
with the .java suffix.
You can use the command-line options described in Table 1-2 to include additional functionality in the
standard compile command. This is only a partial list of options; for acomplete list, including some that may
be specific to the Java compiler implementation, enter javac –help at the command line.


Table 1-2. Standard Options Supported by Java Compilers
Option Description
–classpath This command, followed by a user-specific class path, overrides the system CLASSPATH
environment variable.
–d This command, followed by a directory path, sets the destination directory for the
class files generated by the compiler.
–deprecation This command displays a description of any deprecated methods or classes used in
the source code.
–encoding This command sets the source file encoding name. Otherwise, the default
encoding is used.
–g This command provides more complete debugging information, including local
variable information.
–g:none This command turns off all debugging information.
–g:keyword This command allows the user to specify the type of debugging information provided.
Valid keyword options are source,lines, andvars.
–help This command displays information about the compiler utility options.

–nowarnThis command prevents warning messages from being displayed. Warnings occur
when the compiler suspects something is wrong with the source code but the
problem isn’t severe enough to stop compilation.
–sourceThis command indicates that features added after the specified release aren’t
supported. For example, specifying
–source 1.3will cause the compiler to fail if it
encounters the assert keyword, since assertions weren’t available until Java 1.4.
–sourcepath This command, followed by a source path, specifies the path that the compiler will
use to search for source code files.
–verbose This command produces additional information about the classes that are loaded
and the source files that were compiled.
–X This command displays information about nonstandard options. These are
options that need not be implemented by a compiler to be considered a valid
implementation, and as such may or may not be supported by a given compiler
implementation.



The Java Interpreter
The java utility launches a Java application by loading and running the class filecontaining the main
method of the application. The java utility will interpret the bytecode contained in that file and any other
class files that are part of the application. The general command syntax forthe java utility is as follows:
java [options] class [arguments]
Alternatively, you can run it as follows:
java [options] –jar file.jar [arguments]
You can provide the initial class file as a separate file or as part of aJava Archive ( JAR) file. The options
are command-line options for the JVM, and the class is the name of the class file containing the static
main() method to execute. The arguments are any arguments that need to be passed to main().
Table 1-3 describes some of the standard options for the java utility and, as with the compiler, you can
enter java –help at the command line to see a complete set of options supported by theimplementation
you’re using.

 Table 1-3.Standard Options Supported by JVM Implementations
Option Description
–client This command specifies that the Java HotSpot Client Virtual
Machine should be used. This is the default and is optimized for
executing client/desktop application code.
–server This command specifies that the Java HotSpot Server Virtual
Machine should be used. This Virtual Machine is optimized
for executing server code, such as that used to support web
applications.
–classpath or –cp This command, followed by a user-specified class path, overrides
the system CLASSPATH environment variable.
–Dproperty=value This command provides a system property with a value.
–enableassertions or –ea This command enables assertions, which are disabled by default.
–disableassertions or –da This command disables assertions.
–enablesystemassertions or –esa This command enables assertions in all system classes.
–disablesystemassertions or –dsa This command disables assertions in all system classes.
–help or –? This command displays information about the java utility.
–jar This command executes a program contained in a JAR file, as
shown previously.
–showversion This command shows version information and continues running.
–verbose This command provides information about each class that’s loaded.
–verbose:gc This command reports garbage collection events.
–verbose:jni This command displays information about native methods and
other JNI activity.
–version This command shows version information and then exits.
–showversion This command shows the version number and then continues.
–X This command displays information about nonstandard options
and then exits.

 


The Java ClassDisassembler
You can use the javap utility to look inside a class file, whichcan be helpful if you want to have only
the compiled code and want to want to understand what the source code lookedlike or if you want to
understand how Java source code is mapped to bytecode. The standard commandlists declarations of
nonprivate and nonstatic fields, methods, constructors, and static initializersfor a specific class file. You
can also use the javap utility to provide a printout of the JVM bytecode instructions that areexecuted for
each method as we did earlier in the chapter to examine the bytecodes generatedby compiling the source.
The basic syntax for the javap command is as follows:
javap [options] class




The options are command-line options for the javap utility (see Table 1-4).



 Table 1-4.Some of the Options Supported by the javap Utility
Option Description
–b This command ensures backward compatibility with earlier versions of javap.
–bootclasspath This command, followed by a path, specifies the path from which to load the
bootstrap classes. Normally these would be classes contained in the
/lib/rt.jar archive.
–c This command prints the JVM instructions for the execution of each method.
This tells you what the bytecode for each method actually does.
–classpath This command, followed by a user-specified class path, overrides the system
CLASSPATH environment variable.
–extdirs This command, followed by a directory, overrides the location the system searches
for installed extensions. The default location is /lib/ext.
–help This command prints information about the javap utility.
–Jflag This command passes the specified flag directly to the runtime system.
–l This command displays line and local variables.
–package This command shows only package, protected, and public classes and members.
This is the default.
–private This command shows information about all classes and members.
–protected This command displays information about protected and public classes and
members only.
–public This command shows information only about public classes and members.
–s This command prints internal type signatures.
–verbose This command prints additional information for each method including stack size,
local variable information, and arguments.



0 0
原创粉丝点击