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>.



Sunday, October 27, 2013

Web Services


  • Web services are application components
  • Web services communicate using open protocols
  • Web services are self-contained and self-describing
  • Web services can be discovered using UDDI
  • Web services can be used by other applications
  • HTTP and XML is the basis for Web services
·         Web services can be published, found, and used on the Web.
·         Web services use XML to code and to decode data, and SOAP to transport it (using open protocols)
·          

WSDL
  • WSDL stands for Web Services Description Language
  • WSDL is an XML-based language for describing Web services.
  • WSDL is a W3C recommendation
SOAP?
  • SOAP stands for Simple Object Access Protocol
  • SOAP is a communication protocol
  • SOAP is for communication between applications
  • SOAP is a format for sending messages
  • SOAP communicates via Internet
  • SOAP is platform independent
  • SOAP is language independent
  • SOAP is based on XML
  • SOAP is simple and extensible
  • SOAP allows you to get around firewalls
  • SOAP is a W3C recommendation

Why SOAP?

It is important for application development to allow Internet communication between programs.
Today's applications communicate using Remote Procedure Calls (RPC) between objects like DCOM and CORBA, but HTTP was not designed for this. RPC represents a compatibility and security problem; firewalls and proxy servers will normally block this kind of traffic.
A better way to communicate between applications is over HTTP, because HTTP is supported by all Internet browsers and servers. SOAP was created to accomplish this.
SOAP provides a way to communicate between applications running on different operating systems, with different technologies and programming languages.
Syntax Rules
Here are some important syntax rules:
  • A SOAP message MUST be encoded using XML
  • A SOAP message MUST use the SOAP Envelope namespace
  • A SOAP message MUST use the SOAP Encoding namespace
  • A SOAP message must NOT contain a DTD reference
  • A SOAP message must NOT contain XML Processing Instructions

UDDI
  • UDDI stands for Universal Description, Discovery and Integration
  • UDDI is a directory service where companies can search for Web services.
  • UDDI is described in WSDL
  • UDDI communicates via SOAP

1. What is differences between RESTful web services and SOAP web services ?
Ans:Though both RESTful web service and SOAP web service can operate cross platform they are architecturally different to each other, here is some of differences between REST and SOAP:
1) REST is more simple and easy to use than SOAP. REST language is based on use of nouns and verbs (better readability)
2) REST uses HTTP protocol for producing or consuming web services while SOAP uses XML.

  • The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S),  Messaging, TCP, UDP SMTP, etc.
  • The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.
3) REST is lightweight as compared to SOAP and preferred choice in mobile devices and PDA's. REST does not need XML parsing, no message header (to and from), hence less bandwidth
4) REST supports different format like text, JSON and XML while SOAP only support XML.

  • The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service.
  • The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations.
         GET - represent()
         POST - acceptRepresention()
         PUT - storeRepresention()
         DELETE - removeRepresention() 
5) SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. 
6) Different error handling:          
    REST: requires HTTP error handling          
    SOAP: can have user defined error
7) REST only supports synchronous  message because of its reliance of HTTP and HTTPS
8) SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. 
The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not.
9) The SOAP has comprehensive support for both ACID based  transaction management  for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. 
The REST supports transactions, but it  is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.
10) The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.

Security Certificates

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