Beruflich Dokumente
Kultur Dokumente
28 Constant Expression A compile-time constant expression is an expression denoting a value of primitive type or a String that is composed using only the following:
Literals of primitive type and literals of type String Casts to primitive types and casts to type String The unary operators +, -, ~, and ! (but not ++ or --) The multiplicative operators *, /, and % The additive operators + and The shift operators <<, >>, and >>> The relational operators <, <=, >, and >= (but not instanceof) The equality operators == and != The bitwise and logical operators &, ^, and | The conditional-and operator && and the conditional-or operator || The ternary conditional operator ? : Simple names that refer to final variables whose initializers are constant expressions
Qualified names of the form TypeName . Identifier that refer to final variables whose initializers are constant expressions
f a extends the Java Collections Framework by providing type-specific maps,
sets, lists and queues with a small memory footprint and fast access and insertion; provides also big (64-bit) arrays, sets and lists, and fast, practical I/O classes for binary and text files. It is free software distributed under the Apache License 2.0. It requires Java 6 or newer. The classes implement their standard counterpart interface (e.g., Mp maps) a for and can be plugged into existing code. Moreover, they provide additional features (such as bidirectional iterators) that are not available in the standard classes. Besides objects and primitive types, f a classes provide support for references, that is, objects that are compared using the equality operator rather than the eqls method. u a The sources are generated using a C preprocessor, starting from a set of driver files. You can peek at thejv o -generated documentation. In particular, the ad a overview explains the design choices used in fs t .t .au
extended to big arrays: have a look at the Javadoc documentation of BigArrays andI n to get g an idea of the generic and type-specific methods available.
Java 5
The release 5 of fneeds Java 5, and marks a revolution in the way the classes au st t are organized. Besides full support for generics, which can help with objectbased classes (but is rather irrelevant in type-specific classes),fsunow is at i l t strongly based on what is probably the less hyped and most important feature of Java 5:covariant return-type overriding. A method x) ( returning an object of type T can now be overriden by a method returning an object of type U where U a subclass of (or implements) T , is . Covariant return-type overriding has always been supported by the JVM, but was inaccessible at the syntax level. In Java 5 this irritating limitation has been lifted, opening a new world of clarity and orthogonality in organizing collection classes. In particular, interface strengthening makes it possible to use all features of fs classes without type a t casting: for instance, It strengthened, w.r.t. S so that it returns an I is n S ,e n instead of a simple Ie .tr Although type casting was previosuly used to simulate this feature, it made using the hundreds of classes in fsu difficult and error-prone, as every a t t type cast had to be checked against the documentation. Another advantage of covariant return-type overriding is that implementations can declare to return more specific (usually, more powerful) types than those specified by their interface. For instance, ItL returns actually nT AV i . t S e r an In ,t L whereas Iisrspecified as returning just anI ai nt te So i . S d .ntB l n o i t c e r i d
TLABs
Thread-Local Allocation Buffers Each application thread gets a TLAB to allocate into
> TLABs allocated in the Eden > Bump-a-pointer allocation; fast > No synchronization (thread owns TLAB for allocation)
Disabling TLAB will consume more memory and make program slower.
java -XX:-UseTLAB com.dawidweiss.examples.Example07
Memory allocation is usually very fast and optimized. Dont play with various garbage collectors, its not worth it, instead. . . Allocate memory statically if high-performance is needed, and. .Dump and inspect GC activity with -verbose:gc and other options.
} }.start(); } public static void main(String[] args) { startThread(); System.out.println("Entering the loop..."); while (!ready) { // Do nothing. } System.out.println("Done, I left the loop!");
optimizatio
-XX:+PrintInlining
ns
C1: _ fast _ not (much) optimization C2: _ slow(er) than C1 _ a lot of JMM-allowed optimizations What about javac -O option?....it is only for backward compatibility
Most Java calls are monomorphic. HotSpot adjusts to megamorphic calls automatically
public void testAdd1() { int sum = 0; for (int i = 0; i < COUNT; i++) { sum += add1(i); } guard = sum; } public int add1(int i) { return i + 1; }
... -XX:+PrintInlining ... ... Inlining intrinsic _bitCount_i at bci:9 in ..Example06::testBitCount1 Inlining intrinsic _bitCount_i at bci:9 in ..Example06::testBitCount1 Inlining intrinsic _bitCount_i at bci:9 in ..Example06::testBitCount1 Example06.testBitCount1: [measured 10 out of 15 rounds] round: 0.07 [+- 0.00], round.gc: 0.00 [+- 0.00] ... @ 9 com.dawidweiss.geecon2010.Example06::bitCount inline (hot) @ 9 com.dawidweiss.geecon2010.Example06::bitCount inline (hot) @ 9 com.dawidweiss.geecon2010.Example06::bitCount inline (hot) Example06.testBitCount2: [measured 10 out of 15 rounds] round: 0.32 [+- 0.01], round.gc: 0.00 [+- 0.00] ...
... -XX:+PrintOptoAssembly ... {method} - klass: {other class} - method holder: com/dawidweiss/geecon2010/Example06 - name: testBitCount1 ... 0c2 B13: # B12 B14 <- B8 B12 Loop: B13-B12 inner stride: ... 0c2 movl R10, RDX # spill ... 0e1 movl [rsp + #40], R11 # spill 0e6 popcnt R8, R8 ... 0f5 addl R9, #7 # int 0f9 popcnt R11, R11 0fe popcnt RCX, R9
On platforms typically used for client applications, the JDK comes with a VM implementation called the Java HotSpot Client VM (client VM). The client VM is tuned for reducing start-up time and memory footprint. It can be invoked by using the client command-line option when launching an application.
On all platforms, the JDK comes with an implementation of the Java virtual machine called the Java HotSpot Server VM (server VM). The server VM is designed for maximum program execution speed. It can be invoked by using the -server commandline option when launching an application. Some features of Java HotSpot technology, common to both VM implementations, are the following.
Adaptive compiler - Applications are launched using a standard interpreter, but the code is then analyzed as it runs to detect performance bottlenecks, or "hot spots". The Java HotSpot VMs compile those performance-critical portions of the code for a boost in performance, while avoiding unnecessary compilation of seldom-used code (most of the program). The Java HotSpot VMs also use the adaptive compiler to decide, on the fly, how best to optimize compiled code with techniques such as in-lining. The runtime analysis performed by the compiler allows it to eliminate guesswork in determining which optimizations will yield the largest performance benefit. Rapid memory allocation and garbage collection - Java HotSpot technology provides for rapid memory allocation for objects, and it offers a choice of fast, efficient, state-of-the-art garbage collectors.
Thread synchronization - The Java programming language allows for use of multiple, concurrent paths of program execution (called "threads"). Java HotSpot technology provides a thread-handling capability that is designed to scale readily for use in large, shared-memory multiprocessor servers.
In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and lessw data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences. The GarbageFirst (G1) garbage collector is experimental in this release. Some command line tools, such as jstack or jmap, may not work properly when using the G1 collector. In previous releases of the JDK on Solaris only, the Thread.interrupt() method would interrupt some blocking I/O operatons resulting in InterruptedIOException thrown by the target thread and leaving socket or file streams in an inconsistent state. This so called "legacy interruptible I/O support" has been disabled in JDK 7. Applications that previously relied on this Solaris specific behavior can re-enable this support by running with the following option on the command line: -XX:+UseVMInterruptibleIO. A future release of the JDK may remove the legacy interruptible I/O support completely.
------------------------------------------------------------------------------------------------------------------------disableassertions[:<package name>"..." | :<class name> ] -da[:<package name>"..." | :<class name> ] Disable assertions. This is the default. With no arguments, disableassertions or -da disables assertions. With one argument ending in "...", the switch disables assertions in the specified package and any subpackages. If the argument is simply "...", the switch disables assertions in the unnamed package in the current working directory. With one argument not ending in "...", the switch disables assertions in the specified class. To run a program with assertions enabled in package com.wombat.fruitbat but disabled in class com.wombat.fruitbat.Brickbat, the following command could be used:
-verbose:class Display information about each class loaded. -verbose:gc Report on each garbage collection event. -verbose:jni Report information about use of native methods and other Java Native Interface activity. -Xfuture Perform strict class-file format checks. For purposes of backwards compatibility, the default format checks performed by the Java 2 SDK's virtual machine are no stricter than the checks performed by 1.1.x versions of the JDK software. The -Xfuture flag turns on stricter class-file format checks that enforce closer conformance to the class-file format specification. Developers are encouraged to use this flag when developing new code because the stricter checks will become the default in future releases of the Java application launcher. -Xnoclassgc Disable class garbage collection. Use of this option will prevent memory recovery from loaded classes thus increasing overall memory usage. This could cause OutOfMemoryError to be thrown in some applications. -Xincgc Enable the incremental garbage collector. The incremental garbage collector, which is off by default, will reduce the occasional long garbage-collection pauses during program execution. The incremental garbage collector will at times execute concurrently with the program and during such times will reduce the processor capacity available to the program. -Xloggc:file Report on each garbage collection event, as with -verbose:gc, but log this data to file. In addition to the information -verbose:gc gives, each reported event will be preceeded by the time (in seconds) since the first garbage-collection event. Always use a local file system for storage of this file to avoid stalling the JVM due to network latency. The file may be truncated in the case of a full file system and logging will continue on the truncated file. This option overrides -verbose:gc if both are given on the command line. -Xmnsize or -XX:NewSize Sets the size of the young generation (nursery). -Xmsn Specify the initial size, in bytes, of the memory allocation pool. This value must be a multiple of 1024 greater than 1MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is chosen at runtime based on system configuration.
-Xms6291456 -Xms6144k
-Xmxn
-Xms6m
Specify the maximum size, in bytes, of the memory allocation pool. This value must be a multiple of 1024 greater than 2MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is chosen at runtime based on system configuration. For server deployments, -Xms and -Xmx are often set to the same value.
-Xprof Profiles the running program, and sends profiling data to standard output. This option is provided as a utility that is useful in program development and is not intended to be used in production systems.
-Xrs Reduces usage of operating-system signals by the Java virtual machine (JVM). This option is available beginning with J2SE 1.3.1. In J2SE 1.3.0, the Shutdown Hooks facility was added to allow orderly shutdown of a Java application. The intent was to allow user cleanup code (such as closing database connections) to run at shutdown, even if the JVM terminates abruptly. The JVM watches for console control events to implement shutdown hooks for abnormal JVM termination. Specifically, the JVM registers a console control handler which begins shutdown-hook processing and returns TRUE for CTRL_C_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, and CTRL_SHUTDOWN_EVENT. The JVM uses a similar mechanism to implement the pre-1.2 feature of dumping thread stacks for debugging purposes. Sun's JVM uses CTRL_BREAK_EVENT to perform thread dumps. If the JVM is run as a service (for example, the servlet engine for a web server), it can receive CTRL_LOGOFF_EVENT but should not initiate shutdown since the operating system will not actually terminate the process. To avoid possible interference such as this, the -Xrs command-line option has been added beginning with J2SE 1.3.1. When the -Xrs option is used on Sun's JVM, the JVM does not install a console control handler, implying that it does not watch for or process CTRL_C_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, or CTRL_SHUTDOWN_EVENT. There are two consequences of specifying -Xrs:
-Xssn
Ctrl-Break thread dumps are not available. User code is responsible for causing shutdown hooks to run, for example by calling System.exit() when the JVM is to be terminated.
Set thread stack size. -XX:AllocationPrefetchStyle=n Sets the style of prefetch used during allocation. default=2. -XX:+AggressiveOpts Enables aggressive optimization. -XX:+|-DisableAttachMechanism This option specifies whether tools (such as jmap and jconsole) are allowed to attach to the JVM. By default, this feature is disabled. That is, attaching is enabled. Example usage:
java -XX:+DisableAttachMechanism
-XXLargePageSizeInBytes=n This option specifies the maximum size for large pages. -XX:MaxGCPauseMillis=n
Sets a target for the maximum GC pause time. This is a soft goal, and the JVM will make its best effort to achieve it. There is no maximum value set by default. -XX:NewSize Sets the size of the young generation (nursery). Sames as -Xmnsize. -XX:ParallelGCThreads=n Sets the number of GC threads in the parallel collectors. -XX:PredictedClassLoadCount=n This option requires that the UnlockExperimentalVMOptions flag be set first. Use the PredictedClassLoadCount flag if your application loads a lot of classes, and especially if class.forName() is used heavily. The recommended value is the number of classes loaded as shown in the output from -verbose:class. Example usage:
Enables the parallel garbage collectors, which are optimized for throughput and average response time. NOTES: The -version:release command line option places no restrictions on the complexity of the release specification. However, only a restricted subset of the possible release specifications represent sound policy and only these are fully supported. These policies are: 1. 2. Any version, represented by not using this option. Any version greater than an arbitrarily precise version-id. For example:
3. "1.6.0_10+"
Would utilize any version greater than 1.6.0_10. This is useful for a case where an interface was introduced (or a bug fixed) in the release specified. 4. A version greater than an arbitrarily precise version-id, bounded by the upper bound of that release family. For example:
EXIT STATUS
The following exit values are generally returned by the launcher, typically when the launcher is called with the wrong arguments, serious errors, or exceptions thrown from the Java Virtual Machine. However, a Java application may choose to return any value using the API call System.exit(exitValue).
LiveLock
Livelock occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available. In terms of Java API, thread livelock can occur in following conditions:
When all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify() or Object.notifyAll() on the relevant objects. Because all the threads are blocked, neither call can be made. When all the threads in a program are stuck in infinite loops.
Starvation
Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked. Starvation occurs when one thread cannot access the CPU because one or more other threads are monopolizing the CPU. In Java, thread starvation can be caused by setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time.
How to find a deadlock has occurred in Java? How to detect a Deadlock in Java?
Earlier versions of Java had no mechanism to handle/detect deadlock. Since JDK 1.5 there are some powerful methods added in the java.lang.management package to diagnose and detect deadlocks. The java.lang.management.ThreadMXBean interface is management interface for the thread system of the Java virtual machine. It has two methods which can leveraged to detect deadlock in a Java application.
findMonitorDeadlockedThreads() - This method can be used to detect cycles of threads that are in deadlock waiting to acquire object monitors. It returns an array of thread IDs that are deadlocked waiting on monitor. findDeadlockedThreads() - It returns an array of thread IDs that are deadlocked waiting on monitor or ownable synchronizers.
How to find a deadlock has occurred in Java? How to detect a Deadlock in Java?
Earlier versions of Java had no mechanism to handle/detect deadlock. Since JDK 1.5 there are some powerful methods added in the java.lang.management package to diagnose and detect deadlocks. The java.lang.management.ThreadMXBean interface is management interface for the thread system of the Java virtual machine. It has two methods which can leveraged to detect deadlock in a Java application.
findMonitorDeadlockedThreads() - This method can be used to detect cycles of threads that are in deadlock waiting to acquire object monitors. It returns an array of thread IDs that are deadlocked waiting on monitor. findDeadlockedThreads() - It returns an array of thread IDs that are deadlocked waiting on monitor or ownable synchronizers.