Java / JDK, JRE, JVM, JIT
Java programs are compiled to generate byte-code which is .class file. This byte-code files are interpreted by the architecture specific JVM to execute that makes java programs run in any type of hardware.
JAVA supports WORA which make it run across different platform/operating system.
Java is an easy to understand and simple to learn.
High level languages(HLL) are languages that has less complexity and easy to understand, as the syntax are close to human language and it abstracts the machine language.
ME(Micro Edition) for mobile,
SE(Standard Edition) for desktops,
and EE(Enterprise edition) for enterprise.
Java is a high-level programming language and object oriented. It was developed by Sun Micro systems, initially released in 1995.
Java is object based as we cannot create any program without creating a class.
JVM
JVM is Java Virtual Machine, it provides the runtime environment in which java bytecode can be executed. JVMs are available for many hardware and software platforms (so JVM is platform dependent).
JRE
JRE is Java Runtime Environment. It is the implementation of JVM.
JRE doesn't have Javac compiler.
JDK
JDK is Java Development Kit. It exists physically and contains JRE and development tools.
Yes.
There are 12 buzzwords.
- Simple.
- Object-Oriented.
- Platform independent.
- Secured.
- Robust.
- Architecture neutral.
- Portable.
- Dynamic.
- Interpreted.
- High Performance.
- Multithreaded.
- Distributed.
The Java compiler generates byte-codes, rather than native machine code. To run a Java program, you use the Java interpreter to execute the compiled byte-codes. Java byte-codes provide an architecture-neutral object file format. The code is designed to transport programs efficiently to multiple platforms.
Many types:
Class(Method) Area,
Heap,
Stack,
Program Counter Register,
Native Method Stack.
Java 10 released on March 20, 2018.
WORA refers to the ability of a computer program to run across any operation system or platform.
Platform refers to any hardware/software environment under which a program runs.
Java has primitive data types which are not objects, so Java is considered as not fully object oriented language. However Java could be considered as fully object oriented language as it has wrapper classes for its primitive types.
Java is secured for developing application due to many of security features that includes, Byte-code verification before execution, Run time security checks, Immutable classes (String for e.g.)
Bytecode is a highly optimized set of instructions, low level language and non-executable code. The platform specific JVM interprets bytecode to run the program.
Being platform independent and architecture neutral, Java application developed in one enviroment can be deployed to different platform and executed using compliant JVM. Java application developed for Desktops(SE) are fully portal where Java EE has EJB which makes it less portal.
- highly supported language and portable,
- Strongly typed language,
- Memory Management,
- Garbage Collection,
- Exception Handling,
- No pointers.
Java was designed to adapt to an evolving/changing environment. Even after binaries have been released, they can adapt to a changing environment. Java loads in classes as they are needed, even from across the network It defers many decisions (like object layout) to runtime, which solves many of the version problems that C++ has.
Although Java is an interpreted language, it is faster than other interpreted languages. JITC ( Just in Time compilation) is one such feature that enables Java as high-performance language (HPC).
Java is inherently multi-threaded. A single Java program can have many different threads executing independently and continuously.
Java application can be distributed and the implementation of variable protocols enables effective communication.
The classloader, a subsystem of JVM, is used to load classes and interfaces.
There are many types of classloaders e.g.
- Bootstrap,
- Extension,
- System,
- Plugin.
Java Virtual Machine(JVM) gets some memory from the underlying operating system to run any java program. This memory is referred as Java heap.
Heap in Java located at bottom of address space and move upwards. When an object is created using new operator or by any other means object is allocated memory from Heap and when the object is garbage collected, memory goes back to Heap space in Java and get reused.
Default maximum heap space is 1/2 of physical memory of size upto 192 bytes and 1/4th of physical memory for size upto 1Gig. So for 1Gig machine maximum heap size is 256MB 2.maximum heap size will not be used until program creates enough object to fill initial heap space which will be much lesser but at-least 8 MB or 1/64th part of Physical memory upto 1GB.
For Servers, Java virtual machine default maximum heap space is 1G for 4GB of physical memory on a 32 bit JVM. for 64 bit JVM its 32G for a physical memory of 128GB.
The Java memory model specifies how the Java virtual machine works with the computer's memory (RAM).
- Lambda Expressions,
- Interface Default and Static Methods,
- Method Reference,
- Parameters Name,
- Optional feature,
- Streams,
- and Concurrency.
J2EE defines three types of archives.
- Java Archive (JAR) A JAR file encapsulates one or more Java classes, a manifest, and a descriptor. JAR files are the lowest level of archive. JAR files are used in J2EE for packaging EJBs and client-side Java Applications.
- Web Archive (WAR) A WAR files are similar to JAR files, except that they are specifically for web applications made from Servlets, JSPs, and supporting classes. Struts and Spring based Web applications may be archived to a WAR.
- Enterprise Archive (EAR) An EAR file contains all of the components that make up a particular J2EE application. A EAR may contain one or more WAR files. EAR files can also contain connector modules packaged as RAR files and Client modules packaged as JAR files.
Memory leak in Java refers to a situation where some objects are not used by the application any more, but GC fails to recognize them as unused. As a result, these objects remain in memory indefinitely, reducing the amount of memory available to the application.
Every Java object tree must have one or more root objects. As long as the application can reach those roots, the whole tree is reachable.
There are some objects which are considered ?important? by GC. These are called GC roots and are (almost) never discarded. They are, for example, currently executing method's local variables and input parameters, application threads, references from native code and similar ?global? objects. Any object referenced from those GC roots are assumed to be in use and not discarded.
There are 4 different kinds of GC roots in Java.
- Local variables,
- Active Java threads,
- Static variables,
- and JNI References.
OutOfMemoryError is one of the symptom to be diagnosed as it could lead to memory leaks.
Application may crash without issuing OutOfMemoryError.
- Identify symptoms,
- Enable verbose garbage collection using -verbosegc argument,
- Enable profiling,
- Analyze the trace.
The main difference between heap and stack is that stack memory is used to store local variables and function call while heap memory stores objects in Java.
Each Thread in Java has its own stack whose size can be specified using -Xss JVM parameter, similarly, you can also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is the starting size of the heap and -Xmx is the maximum size of java heap.
If there is no memory left in the stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating an object, JVM will throw java.lang.OutOfMemoryError: Java Heap Space.
Size of stack memory is a lot lesser than the size of heap memory in Java.
Variables stored in the stack are only visible to the owner thread while objects created in the heap are visible to all threads. Stack memory is a private memory of a Java Thread while heap memory is shared among all threads.
Stack | Heap |
Stack memory is used only by one thread of execution. | Heap memory is used by all the parts of the application. |
Stack memory cannot be accessed by other threads. | Objects stored in the heap are globally accessible. |
Follows LIFO manner to free memory. | Memory management is based on the generation associated with each object. |
Exists until the end of execution of the thread. | Heap memory lives from the start till the end of application execution. |
Stack memory only contains local primitive and reference variables to objects in heap space. | Whenever an object is created, itÂ’s always stored in the Heap space. |
GC sweeps heap memory only. Usually, stack memory is collected automatically when the execution path reaches the end of the scope.
Garbage collection relieves programmers from the burden of freeing allocated memory.
GC helps ensure program integrity. Garbage collection is an important part of Java's security strategy.
Because Java's garbage collector runs in its own thread, in most cases, it will run transparently alongside the execution of a program.
GC algorithms can be divided into 3 categories: sweeping, compacting and copying.
The Serial GC recommended for client-style applications that do not have low pause time requirements.
The Parallel GC - use when the throughput matters.
The Mostly-Concurrent GC (also known as Concurrent Mark-Sweep GC(CMS)) - use when the latency matters.
The Garbage First GC (G1) - new GC algorithm, for CMS replacement.
Parallel GC. It is faster compared to the other algorithms.
Java provides 4 different types of Reference Objects: strong, weak, soft and phantom.
Strong reference : This reference is something that we use daily while writing the code. Any object in the memory which has active strong reference is not eligible for garbage collection.
For example String s = "abc" , reference variable s has strong reference to String object "abc". Any object which has Strong reference attached to it is not eligible for garbage collection.
Weak Reference are represented using java.lang.ref.WeakReference class and you can create Weak Reference by using following code.
WeakReference<StringBuilder> weakBuilder = new WeakReference<StringBuilder>(builder);
A weak reference is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself.
Serial garbage collector works by holding all the application threads. It is designed for the single-threaded environments. It uses just a single thread for garbage collection. The way it works by freezing all the application threads while doing garbage collection may not be suitable for a server environment. It is best suited for simple command-line programs.
Run with -XX:+UseSerialGC JVM argument to use the serial garbage collector.
Serial GC is recommended for client-style applications that do not have low pause time requirements.
Parallel garbage collector also called as throughput collector, is the default garbage collector of the JVM. Unlike serial garbage collector, this uses multiple threads for garbage collection. Similar to serial garbage collector this also freezes all the application threads while performing garbage collection.
Turn on the -XX:+UseParallelGC JVM argument to use the CMS garbage collector.
The Parallel GC is recommended for situations where high throughput required.
Concurrent Mark Sweep (CMS) garbage collector uses multiple threads to scan the heap memory to mark instances for eviction and then sweep the marked instances. CMS garbage collector holds all the application threads in the following two scenarios only,
- While marking the referenced objects in the tenured generation space.
- If there is a change in heap memory in parallel while doing the garbage collection.
CMS collector uses more CPU to ensure better application throughput. If we can allocate more CPU for better performance then CMS garbage collector is the preferred choice over the parallel collector.
Turn on the XX:+USeParNewGC JVM argument to use the CMS garbage collector.
G1 garbage collector is used for large heap memory areas. It separates the heap memory into regions and does collection within them in parallel. G1 also does compacts the free heap space on the go just after reclaiming the memory. But CMS garbage collector compacts the memory on stop the world (STW) situations. G1 collector prioritizes the region based on most garbage first.
Turn on the -XX:+UseG1GC JVM argument to use the G1 garbage collector.
A soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it are WeakReferences) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.
A phantom reference is quite different than either SoftReference or WeakReference. Its grip on its object is so tenuous that you can't even retrieve the object -- its get() method always returns null. The only use for such a reference is keeping track of when it gets enqueued into a ReferenceQueue, as at that point you know the object to which it pointed is dead.
The javap command disassembles one or more class files. javap prints out the package, protected, and public fields and methods of the classes passed to it. javap prints its output to stdout.
You may use it to find out what methods are available for a class if you don?t have the source code that was used to create the class.
javap [options] JavaClassName
PermGen stands for permanent generation space.
PermGen is a memory pool containing all the reflective data of the java virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas. The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application.
The permanent generation is populated by the JVM at runtime based on classes in use by the application. In addition, Java SE library classes and methods may be stored here.
PermGen has been completely replaced by MetaSpace in Java8, a native memory to store class meta-data information and that grows automatically.
We don't encounter OutOfMemoryError in Java 1.8, PermSize and MaxPermSize arguments are ignored at the start-up of application. On the contrary these two jvm arguments are now replaced by MetaspaceSize and MaxMetaspaceSize. These two new flags gives us the flexibility to change the value for default size of metaspace and to change the maximum value that this metaspace can take.
Set MetaspaceSize to a value larger than the default, if you know that your applications needs more space for class data. Setting it to a larger size will avoid some number of GCs at startup.
Metaspace auto increases its size by default (up to what the underlying OS provides), while PermGen always has a fixed maximum size.
1. Underscores Between Digits in Numeric Literals.
int ten_million = 10_000_000;
2. Improved Type Inference for Generic Instance Creation using Diamond operator.
Map<String, List<String>> anagrams = new HashMap<String, List<String>>(); // The above statement can be rewritten using Java Diamond operator. Map<String, List<String>> anagrams = new HashMap<>();
3. Handling multiple exceptions in a single catch block.
4. String in Switch Expression.
5. Try-with-resources Statement.
6. Integral Types as Binary Literals.
Using URLClassLoader we can load the jar.
URLClassLoader child = new URLClassLoader (myJarFile.toURL(), this.getClass().getClassLoader()); Class classToLoad = Class.forName ("net.javapedia.MyClass", true, child); Method method = classToLoad.getDeclaredMethod ("methodToCall"); Object instance = classToLoad.newInstance (); Object result = method.invoke (instance);
Synthetic constructs are class, fields, and methods that are not defined in Java source code and created by the Java compiler while compiling.
For switch statement, Java compiler creates a synthetic field that start with $, and also for the local classes which is required by the VM.
Synthetic constructs are also known as dynamic proxy.
Allow @SafeVargs on private instance methods.
Allow effectively final variables to be used as resources in the try-with-resources statement.
Allow the diamond with anonymous classes if the argument type of the inferred type is denotable.
Complete the removal of the underscore from the set of legal identifier names.
Add support for private interface methods.
JDK 9 adds Read-Eval-Print Loop (REPL) functionality to the Java platform.
The jshell tool provides an interactive command-line interface for evaluating declarations, statements, and expressions of the Java programming language. It facilitates prototyping and exploration of coding options with immediate results and feedback.
Java is the plain old java interpreter, you have a console window open all the time. Javaw is a wrapper around java that doesn't open a console window.
java.exe pops up a console window. javaw.exe does not. If you expect text output, you'll need to use java.exe. If the application pops up its own window (For example, Eclipse), you can use javaw.exe.
Nashorn is the new Javascript processing engine for the Java platform that shipped with Java 8. Until JDK 7, the Java platform used Mozilla Rhino for the same purpose as a Javascript processing engine.
You may add the command line option -verbose:class
to your Java process, this will display information about each class loaded.
java -verbose:class
Strong Data typing: The security concern here is that coding errors that would manifest at runtime in dynamically typed languages are resolve at compile time by strongly typed languages such as Java.
Automatic memory management: Reduces the complexity of managing application memory and the rate of exploitation of an entire class of vulnerability.
Byte code verification: Before the virtual machine executed any code,all byte code is run through the verifier. The verifier performs consistency checks to ensure code adheres to platform specifications.
Secure class loading: This key security control is used to support Java security and the sandbox. Secure class loading maintains the control of sandbox trust boundaries and integrity of the programs operating within the sandbox.
Exception handling: This core language feature allows applications to manage application state and execution control during unexpected events.
Authentication and Access control: The platform provides libraries such as Java Authentication and Authorization Service (JAAS) and Java policies to ensure only authorized individuals can change application data.
Protecting Data: Cryptographic controls (digital signature, message digests, ciphers) protect the confidentiality, availability and integrity of application data.
Secure Communications: Libraries such as Java Secure Socket Extension (JSSE), Java GSS-API and JAVA SASL API defend data traversing untrusted network connections.
Trust Management: Public key infrastructure (PKI) is beneficial when establishing trust relationships with collaborating business partners over untrusted networks. Java provides Java CertPath API, PKIX API to help manage trust between collaborators.
Diagnostics Forensics, and Supply chain security: Java provides Java logging API and static analysis tools like the Java Dependency Analysis Tool (jeeps) that identify third party components in the software supply chain.
Secure class loading: .
Avoiding Strings for volatile secrets: Storing passwords in String objects increases the application risk profile since Strings will remain on the heap until garbage collection.
Avoid Deserializing objects from untrusted sources: The serialization framework calls readObject() on each Serializable object to deserialize itself. An attacker may simply include malicious code in the Object's readObject method. This is then executed by Java serialization framework when the object is deserialized.
Java Native Interface (JNI) bypassing Platform Safety Controls And Buffer overflows: JNI offers incredible controls of the virtual machine. but essentially bypasses most platform security controls.
DTD/XML External Entity (XXE): The XXE attack is made possible by weakness in the XML parser that allows attackers to exfilterate sensitive information on the server.
XML Entity Expansion (XEE): A relatively small XML document that expands into an unanticipated large document. Used by attackers to slow/crash an application.