Sunday, March 30, 2014

JAVA

  • JVM- It stands for Java Virtual Machine. JVM is a kind of abstract machine that gives an idea of the time during which the byte code of java can be carried out. Loading a code, verifying the code, then executing the code and finally providing the runtime environment for the code are the four main tasks that JVM performs. JVM is dependent on many software and hardware platforms.
  • JDK- It stands for Java Development Kit. It has physical existence and it contains JRE (Java Runtime Environment) and development tools like javac etc.
  • JRE- It stands for Java Runtime Environment. JRE usually gives an idea of the java runtime environment. Some set of libraries (rt.jar) and some files that are used by JVM during the run time usually make up a JRE. JRE is basically an application of JVM and it also has physical existence.


Modifiers




JVM




Interpreter: takes only one instruction at a time for executionJust-in-time: takes a block of code at once and compile it before execute. so has plenty room for optimization


Rules for Method Overriding

  • The argument list should be exactly the same as that of the overridden method.The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass.The access level cannot be more restrictive than the overridden method's access level. For example: If the superclass method is declared public then the overridding method in the sub class cannot be either private or protected.Instance methods can be overridden only if they are inherited by the subclass.A method declared final cannot be overridden.A method declared static cannot be overridden but can be re-declared.If a method cannot be inherited, then it cannot be overridden.A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.A subclass in a different package can only override the non-final methods declared public or protected.An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.Constructors cannot be overridden.

For overloaded



1. Same Method Name
2. Same Return Type 
3. Different patameters
4. Different access modifiers
5. Different Exceptions

For overriding

1. Same Method Name
2. Same Return Type   if different then "The return type is incompatible with <ParentClass>.<ParentMethod>method()"
3. Same parameters  if different then "The method bmethod(int) of type A must override or implement a supertype method"
4. same or greater access modifiers then "Cannot reduce the visibility of the inherited method from B"
5. same or Different Exceptions means child Exception


1. Opps
Encapsulation
Abstraction
Polymorphism
overriding
overloading
Inheritance
2. JVM
GIT vs Interpiter
Memory Locations
Class Loaders
Execution Engine
3. GC
Ways to eligible for GC
4. Collections
Queues vs Topic
Concurent Map / list/ set

5. Threads
Thread Local
Thread Pool
How many ways to create thread
Syncronized thread
Syncronized static thread
callable
Thread LifeCycle
wait
notify
notifyAll
Sleep
yeild
6. Exception Handling
7. Java version topics
java 1.5
Enum
Generic
ForEach
Queue
Annotations
Autoboxing Unboxing
Var args
Static imports
Covatiant Return types
java 1.6
Navigable Set/Map
java 1.7
Enhancements in HashMap
try with resources
Try with multiple catch
Switch can take string args
java 1.8
Lambda Expressions
Streams
Functional Interface
Interface changes with default / static methods
Java DateTime API(joda.org ==> joda api)
Method Reference / constructor refence by :: operator
predicate,  function, consumer ==> predefined functional interfaces


+------------------------+-------------------------------+----------------+
| Feature | Lombok | Records |
+------------------------+-------------------------------+----------------+
| Immutability | No | Yes |
| Extensibility | Yes | No |
| Boilerplate code | Reduces | Reduces |
| Readability | Can be more difficult to read | Easier to read |
| Robustness | Less robust | More robust |
| Third-Party dependency | Yes | No |
| IDE compatibility | Not easy | Easy |
+------------------------+-------------------------------+----------------+


Important JVM Parameters
Go to start of metadata

Enabling JMX
-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9999 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false
Control Memory Usage
-Xms512m -Xmx1200m -Xss256k -XX:PermSize=256m -XX:MaxPermSize=512m
Large heaps
(lightbulb)
if 4G is max RAM then reduce the heap so with assumption that u have 4G RAM set the following:
-verbose:gc -Xss256k -Xmn512m -Xms3g -Xmx3g -XX:TargetSurviorRatio=80 -XX:+PrintGCTimeStamps -XX:+PrintGCDetails -XX:+PrintGCApplicationStoppedTime -XX:+HeapDumpOnOutOfMemoryError -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=3002
256K thread stack size optimization is related to the L2 processor cache size of 256K

ms : Initial heap memory ,  mx : max heap memory ,   ss: thread stack size (useful when you have lots of threads) , permsize : heap memory used for short lived objects , it is better to collect objects in the young generation instead of making them go through a old generation collection
Enable GC Statistics
-verbose:gc
-XX:-HeapDumpOnOutOfMemoryError
-XX:-PrintGCDetails
-XX:-PrintGCTimeStamps
-XX:-TraceClassUnloading   <-   useful if u need to trace classes getting unloaded due to memeory pressures
Other GC Optimizations
 
 
-Dsun.rmi.dgc.server.gcInterval=900000 -Dsun.rmi.dgc.client.gcInterval=900000Trigger a GC every 15 minutes instead of the default  1 hour in  JDK 6
-serverJVM in server mode
-XX:+UseCompressedOopson 64 bit JVMs memory is managed through 32 bit offsets.
-XX:+OptimizeStringConcatUseful in tomcat which has lots of string manipulations
-XX:+DoEscapeAnalysis
Helps compiler figuring out if synchonized block can be eliminate as in
local variables. Also figures out if object can be allocated on stack

Saturday, March 29, 2014

Java Annotations


  • Annotations are introduced in java along with JDK 1.5, annotations are used to provide META data to the classes, variables, methods of java
  • Annotations are given by SUN as replacement to the use of xml files in java
  • Every annotations is internally an Interface, but the key words starts with @ symbol
  • In hibernate annotations are given to replace hibernate mapping [ xml ] files
  • hibernate borrowed annotations from java persistence API but hibernate it self doesn’t contain its own annotations
  • At j2se level, sun has provided very limited set of annotations like @Override and @Deprecated …etc…




import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

import XXX.AbcImpl;

// This annotation can only be applied to class methods.
// @Target({ElementType.METHOD})

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, ElementType.TYPE })
// Make this annotation accessible at runtime via reflection.
@Retention(RUNTIME)
@Constraint(validatedBy = AbcImpl.class)
public @interface Abc {
public String message() default "{wc.def.notempty.on.trim}";

Class<?>[] groups() default { };

Class<? extends Payload>[] payload() default {};

}




Now is annotated, so we can call this as a @Abc.

Thursday, December 26, 2013

Garbage Collector

Garbage Collector


àIn old languages like c++, programmer is responsible for both creation and destruction of objects.
àBut in JAVA, programmer is responsible for creation of objects and he is not responsible to destruction of useless objects.
àSome people provide assistant which is always running in background for destruction of useless objects. Because of this assistant, the chance of failing java programs (memory problems) is very less.
This assistant is nothing but GARBAGE COLLECTOR.
àHence the main objective of GARBAGE COLLECTOR is to destroy useless objects
The ways to make an object eligible for GC:
àEven though programmer is not responsible for destruction of useless objects, it is always a good programming practice to make an object eligible for GC, if it is no longer required.
1.       Nullifying the Reference Variable:
If an object no longer required then assign null to all its reference variables, then the object automatically eligible for GC.
Student s1= new Student ();
Student s2= new Student ();
NO Object is eligible for GC                                                                                                                                                        
s1=null à one object is eligible for GC i.e. s1
s2=null àtwo objects are eligible for GC i.e. s1 and s2
NOTE: If an object doesn’t contain any references, then the object is eligible for GC.
2.       Re-assigning the reference variable:
If an object is no longer required, then re-assign all its reference variables to some other objects, then the old object is eligible for GC.
Student s1= new Student ();
Student s2= new Student ();
s1=new Student ();
s2=s1àtwo objects are eligible for GC
3.       Objects created inside a method:
Objects created inside a method are by default eligible for GC once method completes.
4.       Island of Isolation:
Class Test{
Test i;
Psvm(String args[]){
Test t1= new Test ();
Test t2= new Test ();
Test t3= new Test ();
No objects are eligible for GC
t1.i=t2;
t2.i=t3;
t3.i=t1;
No objects are eligible for GC
I.e. Island of Isolation
t1=null
t2=null
t3=null
// three objects are eligible for GC
}
}
Note:
1. If an object doesn’t contain any reference then it is always eligible for GC.
2. Even though object contains references still the object is eligible for GC sometimesàISLAND of ISOLATION.

5.       Requesting JVM to run Garbage Collector
1.       While using system class
2.       Total memory
3.       Gc()

http://www.corejavainterviewquestions.com/java-garbage-collection-interview-questions/






Types of Garbage Collectors


Serial Garbage Collector:

To enable Serial Garbage Collector, we can use the following argument:
java -XX:+UseSerialGC -jar Application.java


Parallel Garbage Collector:



To enable Parallel Garbage Collector, we can use the following argument:
java -XX:+UseParallelGC -jar Application.java

CMS Garbage Collector:






Collects only Old Generation.
Does not wait for the old generation to be full.

Advantage:
Very low pause time, as many phases run concurrently with the application.

Disadvantage:
It causes heap fragmentation as there is no compacting phase.
Its pause times scale with the number of live objects its tenured region.

Concurrent Mode Failure:
If the CMS collector is unable to finish reclaiming the unreachable objects before the tenured generation fills up, of if an allocation cannot be satisfied with the available free space blocks in the tenured generation, then the application is paused, and the collection is completed with all the application threads stopped (STW). The inability to complete a collection concurrently is referred to as concurrent mode failure.


G1(Garbage First) Garbage Collector:

New in Java 6. Officially supported in java 7.
G1 is planned as the long-term replacement for the CMS.
A server-style garbage collector, targeted for multiprocessor machines with large memories.
G1 supports heaps larger than 4 GB, and is a parallel, concurrent and incrementally compacting low-pause garbage collector.
With G1, the heap is partitioned into a set of equal-sized heap regions.
A total of approximately 2000 regions, in which each region would be of size 1Mb to 32MB; determined by the JVM.


To enable the G1 Garbage Collector, we can use the following argument:
java -XX:+UseG1GC -jar Application.java

Advantages:
  • Works well with heap sizes of around 6GB or larger, and stable and predictable pause time below 0.5 seconds.
  • The G1 compacts the heap on-the-go, something the CMS collector only does during full STW collections.
  • Also, G1 offers more predictable garbage collection pauses than the CMS collector, and allows users to specify desired pause targets
Allocation (Evacuation) Failure:
As with CMS, the G1 collector runs parts of its collection while the application continues to run and there is a risk that the application will allocate objects faster than the garbage collector can recover free space. In G1, the failure (exhaustion of the Java heap) occurs while G1 is copying live data out of one region (evacuating) into another region. The copying is done to compact the live data. If a free (empty) region cannot be found during the evacuation of a region being garbage collected, then n allocation failure occurs (because there is no space to allocate the live objects from the region being evacuated) and a stop-the-world (STW) full collection is done.




Z Garbage Collector:

This is a scalable, low-latency, fully concurrent GC. It doesn’t stop the application threads at all and can perform all the hard and expensive work concurrently. This is possible because of some new techniques like colored 64-bit references, load barriers, relocation, and remapping. It was introduced with JDK 11 and is intended for applications with large heaps that require low latency.

To enable the Z Garbage Collector, we can use the following argument in JDK versions lower than 15:
java -XX:+UnlockExperimentalVMOptions -XX:+UseZGC Application.java

From version 15 on, we don’t need experimental mode on:
java -XX:+UseZGC Application.java

We should note that ZGC isn’t the default Garbage Collector.

Note:
These guidelines provide only a starting point for selecting a collector because performance is dependent on the size of the heap, the amount of live data maintained by the application, and the number and speed of available processors.

Pause times are particularly sensitive to these factors, so the threshold of 1 second mentioned previously is only approximate; the parallel collector will experience pause times longer than 1 second on many data size and hardware combinations; conversely, the concurrent collector may not be able to keep pauses shorter than 1 second on some combinations.

If the recommended collector does not achieve the desired performance, first attempt to adjust the heap and generation sizes to meet the desired goals.

If performance is still inadequate, then try a different collector; use the concurrent collector to reduce pause times and use the parallel collector to increase overall throughput on multiprocessor hardware.

Selecting a Collector

Serial Collector:
Generally, it is used for small amount of Heap (Approximately 100MB)
It runs in single thread. It is best suited to single processor machines.
If there are no pause time requirements.

Applications with medium-sized to large-sized data sets that are run on multiprocessor or multithreaded hardware.

Parallel Collector:
If peak application performance (Throughput) is the first priority.
If there are no pause time requirements or pauses of 1 second or longer are acceptable.

CMS Collector:
If response time is more important than overall throughput.
If garbage collection pauses must be kept shorter than approximately 1 second.

G1GC:
Applications running today with either the CMS or the ParallelOldGC garbage collector will benefit switching to G1 if the application has one or more of the following traits.
  • Large heap size.
  • Full GC durations are too long or too frequent.
  • The rate of object allocation rate or promotion varies significantly.
  • Undesired long garbage collection or compaction pauses (longer than 0.5 to 1 second)







Sunday, December 15, 2013

JSP


Implicit Objects:

ObjectDescription
requestThis is the HttpServletRequest object associated with the request.
responseThis is the HttpServletResponse object associated with the response to the client.
outThis is the PrintWriter object used to send output to the client.
sessionThis is the HttpSession object associated with the request.
applicationThis is the ServletContext object associated with application context.
configThis is the ServletConfig object associated with the page.
pageContextThis encapsulates use of server-specific features like higher performance JspWriters.
pageThis is simply a synonym for this, and is used to call the methods defined by the translated servlet class.
ExceptionThe Exception object allows the exception data to be accessed by designated JSP.

JSP Directives:


<%@ directive attribute="value" %>

DirectiveDescription
<%@ page ... %>Defines page-dependent attributes, such as scripting language, error page, and buffering requirements.
<%@ include ... %>Includes a file during the translation phase.
<%@ taglib ... %>Declares a tag library, containing custom actions, used in the page


Attributes:


Following is the list of attributes associated with page directive:

AttributePurpose
bufferSpecifies a buffering model for the output stream.
autoFlushControls the behavior of the servlet output buffer.
contentTypeDefines the character encoding scheme.
errorPageDefines the URL of another JSP that reports on Java unchecked runtime exceptions.
isErrorPageIndicates if this JSP page is a URL specified by another JSP page's errorPage attribute.
extendsSpecifies a superclass that the generated servlet must extend
importSpecifies a list of packages or classes for use in the JSP as the Java import statement does for Java classes.
infoDefines a string that can be accessed with the servlet's getServletInfo() method.
isThreadSafeDefines the threading model for the generated servlet.
languageDefines the programming language used in the JSP page.
sessionSpecifies whether or not the JSP page participates in HTTP sessions
isELIgnoredSpecifies whether or not EL expression within the JSP page will be ignored.
isScriptingEnabledDetermines if scripting elements are allowed for use.
<%@ page buffer="16kb" autoFlush="true"  contentType="text/xml" errorPage="MyErrorPage.jsp" import="java.sql.*,java.util.*"  language="java"  session="true"%> 

<%@ page buffer="none" autoFlush="false"   contentType="application/msword" isErrorPage="true" info="test" isThreadSafe="false"  isELIgnored="false" isScriptingEnabled="false"%> 

<%@ include file="webAnalytics.jsp" %> 

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>


TUTORIAL POINT


Monday, November 11, 2013

Commands

MY SQL



mysql -u<username> -p<password> <DB> -h<hostname> < <sqlfilename>

copying schema from one location to another location:desitnation

time mysqldump -h<source_hostname> -u<source_username> -p<source_password> -P<source_port> -R <source_db_schema>| mysql -h<desitnation_hostname> -u<desitnation_username>  -p <desitnation_password> -P<desitnation_port>  <desitnation_db_schema>.



Security Certificates

  1. Cryptography Basics Understand Key Concepts : Encryption, decryption, hashing, and digital signatures. Key terms: confidentiality, inte...