Thursday, 30 November 2017

Java Performance tuning


Overview
Not every application requires tuning. If an application performs as well as expected, you don't need to exert additional efforts to enhance its performance. However, it would be difficult to expect an application would reach its target performance as soon as it finishes debugging. This is when tuning is required. Regardless of the implementation language, tuning an application requires high expertise and concentration. Also, you may not use the same method for tuning a certain application to tune another application. This is because each application has its unique action and a different type of resource usage. For this reason, tuning an application requires more basic knowledge compared to the knowledge required to write an application. For example, you need knowledge on virtual machines, operating systems and computer architectures. When you focus on an application domain based on such knowledge, you can successfully tune an application.
Sometimes Java application tuning requires only changing JVM options, such as Garbage Collector, but sometimes it requires changing the application source code. Whichever method you choose, you need to monitor the process of executing the Java application first. For this reason, the issues this article will deal with are as follows:
•           How can I monitor a Java application?
•           What JVM options should I give?
•           How can I know if modifying source codes is required or not?

Knowledge Required to Tune the Performance of Java Applications

Java applications operate inside Java Virtual Machine (JVM). Therefore, to tune a Java application, you need to understand the JVM operation process. I have previously blogged about Understanding JVM Internals where you can find great insights about JVM.
The knowledge regarding the process of the operation of JVM in this article mainly refers to the knowledge of Garbage Collection (GC) and Hotspot. Although you may not be able to tune the performance of all kinds of Java applications only with the knowledge on GC or Hotspot, these two factors influence the performance of Java applications in most cases.
It is noted that from the perspective of an operating system JVM is also an application process. To make an environment in which a JVM can operate well, you should understand how an OS allocates resources to processes. This means, to tune the performance of Java applications, you should have an understanding of OS or hardware as well as JVM itself.
Another aspect is that knowledge of Java language domain is also important. It is also important to understand lock or concurrency and to be familiar with class loading or object creation.
When you carry out Java application performance tuning, you should approach it by integrating all this knowledge.

JVM distribution model

A JVM distribution model is related with making a decision on whether to operate Java applications on a single JVM or to operate them on multiple JVMs. You can decide it according to its availability, responsiveness and maintainability. When operating JVM on multiple servers, you can also decide whether to run multiple JVMs on a single server or to run a single JVM per server. For example, for each server, you can decide whether to run a single JVM using a heap of 8 GB, or to use four JVMs each using a heap of 2 GB. Of course, you can decide the number of JVMs running on a single server depending on the number of cores and the characteristics of the application. When comparing the two settings in terms of responsiveness, it might be more advantageous to use a heap of 2 GB rather than 8 GB for the same application, for it takes shorter to perform a full garbage collection when using a heap of 2 GB. If you use a heap of 8 GB, however, you can reduce the frequency of full GCs. You can also improve responsiveness by increasing the hit rate if the application uses internal cache. Therefore, you can choose a suitable distribution model by taking into account the characteristics of the application and the method to overcome the disadvantage of the model you chose for some advantages.

JVM architecture

Selecting a JVM means whether to use a 32-bit JVM or a 64-bit JVM. Under the same conditions, you had better choose a 32-bit JVM. This is because a 32-bit JVM performs better than a 64-bit JVM. However, the maximum logical heap size of a 32-bit JVM is 4 GB. (However, actual allocatable size for both 32-bit OS and 64-bit OS is 2-3 GB.) It is appropriate to use a 64-bit JVM when a heap size larger than this is required.


The next step is to run the application and to measure its performance. This process includes tuning GC, changing OS settings and modifying codes. For these tasks, you can use a system monitoring tool or a profiling tool.
It should be noted that tuning for responsiveness and tuning for throughput could be different approaches. Responsiveness will be reduced if stop-the-world occurs from time to time, for example, for a full garbage collection despite a large amount of throughput per unit time. You also need to consider that a trade-off could occur. Such trade-off could occur not only between responsiveness and throughput. You may need to use more CPU resources to reduce memory usage or put up with reduction in responsiveness or throughput. As opposite cases could likewise occur, you need to approach it according to the priority.
 
JVM Options

I will explain how to specify suitable JVM options mainly for a web application server. Despite not being applied to every case, the best GC algorithm, especially for web server applications, is the Concurrent Mark Sweep GC. This is because what matters is low latency. Of course, when using the Concurrent Mark Sweep, sometimes a very long stop-the-world phenomenon could take place due to fractions. Nevertheless, this problem is likely to be resolved by adjusting the new area size or the fraction ratio.
Specifying the new area size is as important as specifying the entire heap size. You had better specify the ratio of the new area size to the entire heap size by using –XX:NewRatio or specify the desired new area size by using the –XX:NewSize option. Specifying a new area size is important because most objects cannot survive long. In web applications, most objects, except cache data, are generated when HttpResponse to HttpRequestis created. This time hardly exceeds a second. This means the life of objects does not exceed a second, either. If the new area size is not large, it should be moved to the old area to make space for newly created objects. The cost for GC for the old area is much bigger than that for the new area; therefore, it is good to set the size of the new area sufficiently.

If the new area size exceeds a certain level, however, responsiveness will be reduced. This is because the garbage collection for the new area is basically to copy data from one survivor area to another survivor area. Also, the stop-the-world phenomenon will occur even when performing GC for the new area as well as the old area. If the new area becomes bigger, the survivor area size will increase, and thus the size of the data to copy will increase as well. Given such characteristics, it is good to set a suitable new area size by referring to theNewRatio of HotSpot JVM by OS.


Measuring the Performance of Applications

The information to acquire to grasp the performance of an application is as follows:
TPS (OPS): The information required to understand the performance of an application conceptually.
Request Per Second (RPS): Strictly speaking, RPS is different from responsiveness, but you can understand it as responsiveness. Through RPS, you can check the time it takes for the user to see the result.
RPS Standard Deviation: It is necessary to induce even RPS if possible. If a deviation occurs, you need to check GC tuning or interworking systems. 
To obtain a more accurate performance result, you should measure it after warming up the application sufficiently. This is because byte code is expected to be compiled by HotSpot JIT. In general, you can measure actual performance values after applying load to a certain feature for at least 10 minutes by using nGrinder load testing tool.

Tuning in Earnest

You don't need to tune the performance of an application if the result of the execution of nGrinder meets the expectation. If the performance does not meet the expectation, you need to carry out tuning to resolve problems. Now you will see the approach by case.

In the event the Stop-the-World takes long

Long stop-the-world time could result from inappropriate GC options or incorrect implementation. You can decide the cause according to the result of a profiler or a heap dump. This means you can judge the cause after checking the type and number of objects of a heap. If you find many unnecessary objects, you had better modify source codes. If you find no particular problem in the process of creating objects, you had better simply change GC options.
To adjust GC options appropriately, you need to have GC log secured for a sufficient period of time. You need to understand in which situation the stop-the-world takes a long time. For more information on the selection of appropriate GC options, read my colleague's blog about How to Monitor Java Garbage Collection.

In the event CPU usage rate is low

When blocking time occurs, both TPS and CPU usage rate will decrease. This might result from the problem of interworking systems or concurrency. To analyze this, you can use an analysis on the result of thread dump or a profiler. For more information on thread dump analysis, read How to Analyze Java Thread Dumps.
You can conduct a very accurate lock analysis by using a commercial profiler. In most cases, however, you can obtain a satisfactory result with only the CPU analyzer in jvisualvm.

In the event CPU usage rate is high

If TPS is low but CPU usage rate is high, this is likely to result from inefficient implementation. In this case, you should find out the location of bottlenecks by using a profiler. You can analyze this by using jvisuavm, TPTP of Eclipse or JProbe.

Approach for Tuning

You are advised to use the following approach to tune applications.
First, you should check whether performance tuning is necessary. The process of performance measuring is not easy work. You are also not guaranteed to obtain a satisfactory result all the time. Therefore, if the application already meets its target performance, you don't need to invest additionally in performance.
The problem lies in only a single place. All you have to do is to fix it. The Pareto principle applies to performance tuning as well. This does not mean to emphasize that the low performance of a certain feature results necessarily from a single problem. Rather, this emphasizes that we should focus on one factor that has the biggest influence on the performance when approaching performance tuning. Thus, you could handle another problem after fixing the most important one. You are advised to try to fix just one problem at a time.
You should consider the balloon effect. You should decide what to give up to get something. You can improve responsiveness by applying cache but if the cache size increases, the time it takes to carry out a full GC will increase as well. In general, if you want a small amount of memory usage, throughput or responsiveness could be deteriorated. Thus, you need to consider what is most important and what is less important.
So far, you have read the method for Java application performance tuning. To introduce a concrete procedure for performance measurement, I had to omit some details. Nevertheless, I think this could satisfy most of the cases for tuning Java web server applications

Happy Learning

Iterator Design Pattern


Motivation
One of the most common data structures in software development is what is generic called a collection. A collection is just a grouping of some objects. They can have the same type or they can be all cast to a base type like object. A collection can be a list, an array, a tree and the examples can continue.
But what is more important is that a collection should provide a way to access its elements without exposing its internal structure. We should have a mechanism to traverse in the same way a list or an array. It doesn't matter how they are internally represented.
The idea of the iterator pattern is to take the responsibility of accessing and passing trough the objects of the collection and put it in the iterator object. The iterator object will maintain the state of the iteration, keeping track of the current item and having a way of identifying what elements are next to be iterated.

Intent
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
The abstraction provided by the iterator pattern allows you to modify the collection implementation without making any changes outside of collection. It enables you to create a general purpose GUI component that will be able to iterate through any collection of the application.

Applicability
Use the Iterator pattern
1. to access an aggregate object's contents without exposing its internal representation.
2. to support multiple traversals of aggregate objects.
3. to provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).

Benefit(s)
1. It supports variations in the traversal of an aggregate.
2. Iterators simplify the Aggregate interface.
3. More than one traversal can be pending on an aggregate.

Happy Learning.

Chain of Responsibility Design Pattern


Motivation
In writing an application of any kind, it often happens that the event generated by one object needs to be handled by another one. And, to make our work even harder, we also happen to be denied access to the object which needs to handle the event. In this case there are two possibilities: there is the beginner/lazy approach of making everything public, creating reference to every object and continuing from there and then there is the expert approach of using the Chain of Responsibility.
The Chain of Responsibility design pattern allows an object to send a command without knowing what object will receive and handle it. The request is sent from one object to another making them parts of a chain and each object in this chain can handle the command, pass it on or do both. The most usual example of a machine using the Chain of Responsibility is the vending machine coin slot: rather than having a slot for each type of coin, the machine has only one slot for all of them. The dropped coin is routed to the appropriate storage place that is determined by the receiver of the command.

Intent
It avoids attaching the sender of a request to its receiver, giving this way other objects the possibility of handling the request too.
The objects become parts of a chain and the request is sent from one object to another across the chain until one of the objects will handle it.

Applicability
Use Chain of Responsibility when
1. more than one object may handle a request, and the handler isn't known a prior. The handler should be ascertained automatically.
2. you want to issue a request to one of several objects without specifying the receiver explicitly.
3. the set of objects that can handle a request should be specified dynamically.

Benefit(s)
1. Reduced coupling.
2. Added flexibility in assigning responsibilities to objects.

Disadvantage(s)
1. Receipt isn't guaranteed.

Happy Learning.

Abstract Factory Design Pattern


Motivation
Modularization is a big issue in today's programming. Programmers all over the world are trying to avoid the idea of adding code to existing classes in order to make them support encapsulating more general information. Take the case of a information manager which manages phone number. Phone numbers have a particular rule on which they get generated depending on areas and countries. If at some point the application should be changed in order to support adding numbers form a new country, the code of the application would have to be changed and it would become more and more complicated.
In order to prevent it, the Abstract Factory design pattern is used. Using this pattern a framework is defined, which produces objects that follow a general pattern and at runtime this factory is paired with any concrete factory to produce objects that follow the pattern of a certain country. In other words, the Abstract Factory is a super-factory which creates other factories (Factory of factories).

Intent
Abstract Factory offers the interface for creating a family of related objects, without explicitly specifying their classes.

Where to use
Abstract Factory should be used when:
A system should be configured with one of multiple families of products
A system should be independent of how its products are created, composed and represented
Products from the same family should be used all together, products from different families ahould not be used together and this constraint must be ensured.
Only the product interfaces are revealed, the implementations remains hidden to the clients.

Common Usage
Examples of abstract factories:
java.awt.Toolkit - the abstract superclass of all actual implementations of the Abstract Window Toolkit. Subclasses of Toolkit are used to bind the various components to particular native toolkit implementations(Java AWT).
javax.swing.LookAndFeel - an abstract swing factory to swithct between several look and feel for the components displayed(Java Swing).
java.sql.Connection - an abstract factory which create Statements, PreparedStatements, CallableStatements,... for each database flavor.
Example: Gui Look & Feel in Java

Applicability
Use the Abstract Factory pattern when
1. a system should be independent of how its products are created, composed, and represented.
2. a system should be configured with one of multiple families of products.
3. a family of related product objects is designed to be used together, and you need to enforce this constraint.
4. you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

Benefit(s)
1. It isolates concrete classes.
2. It makes exchanging product families easy.
3. It promotes consistency among products.

Disadvantage(s)
1. Supporting new kinds of products is difficult.

Happy Learning.

Factory Design Pattern


Motivation
The Factory Design Pattern is probably the most used design pattern in modern programming languages like Java and C#. It comes in different variants and implementations. If you are searching for it, most likely, you'll find references about the GoF patterns: Factory Method and Abstract Factory.

Intent
creates objects without exposing the instantiation logic to the client.
refers to the newly created object through a common interface

Where to use
Factory pattern should be used when: - a framework delegate the creation of objects derived from a common superclass to the factory - we need flexibility in adding new types of objects that must be created by the class

Common Usage
Along with singleton pattern the factory is one of the most used patterns. Almost any application has some factories. Here are a some examples in java:
- factories providing an xml parser: javax.xml.parsers.DocumentBuilderFactory or javax.xml.parsers.SAXParserFactory
- java.net.URLConnection - allows users to decide which protocol to use.

Applicability
Use the Factory Method pattern when 1. a class can't anticipate the class of objects it must create. 2. a class wants its subclasses to specify the objects it creates. 3. classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

Benefit(s)
1. Provides hooks for subclasses.
2. Connects parallel class hierarchies.

Disadvantage(s)
A potential disadvantage of factory methods is that clients might have to subclass the Creator class just to create a particular ConcreteProduct object. Subclassing is fine when the client has to subclass the Creator class anyway, but otherwise the client now must deal with another point of evolution.


Happy Learning.

Singleton Design Pattern


Motivation
Sometimes it's important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.
The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Intent
Ensure that only one instance of a class is created.
Provide a global point of access to the object.

Where to use
Singleton pattern should be used when we must ensure that only one instance of a class is created and when the instance must be available through all the code. A special care should be taken in multi-threading environments when multiple threads must access the same resources through the same singleton object.

Common Usage
There are many common situations when singleton pattern is used:
- Logger Classes
- Configuration Classes
- Accessing resources in shared mode
- Other design patterns implemented as Singletons: Factories and Abstract Factories, Builder, Prototype

Example: Lazy Singleton in Java, Early Singleton in Java

Applicability
Use the Singleton pattern when 1. there must be exactly one instance of a class, and it must be accessible to clients from a wellknown access point. 2. when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

Benefit(s)
1. Controlled access to sole instance.
2. Reduced name space.
3. Permits refinement of operations and representation.
4. Permits a variable number of instances.
5. More flexible than class operations.

Happy Learning.

Friday, 8 September 2017

How to Create alerts in Splunk


The Steps include:


  • Open Search page in Search and Reporting Page.
  • Enter your query for which alerts need to be triggered.for example:
         index = os_web sourcetype = custom-prod-up-ext serviceName=SHARP response=failure                  feature=PCI_DE_TOKENIZATION 
  • Select Save as ---->Alert



  • Next Specify Setting,Triggered Condition,Triggered Action.


  • Select Save.

Enjoy Learning.

Tuesday, 29 August 2017

Java program to check unique number


Sample Program:-


 import java.util.*;  
 import java.io.*;  
 /**  
  * Created by Dixit on 29-08-2017.  
  */  
 public class IsUniqueNumber {  
   public static boolean  
   isUniqueUsingHash(String word)  
   {char[] chars = word.toCharArray();  
     Set<Character> set = new HashSet<Character>();  
     for (char c : chars)  
       if (set.contains(c))  
         return false;  
       else {  
         set.add(c);  
       }  
     return true;  
   }  
   public static boolean  
   isUniqueUsingSort(String word)  
   {char[] chars = word.toCharArray();  
     if (chars.length <= 1)  
       return true;  
     Arrays.sort(chars);  
     char temp = chars[0];  
     for (int i = 1; i < chars.length; i++)  
     {if (chars[i] == temp)  
       return false;  
       temp = chars[i];  
     }  
     return true;  
   }  
   public static void main(String[] args)  
       throws IOException  
   {  
     System.out.println(isUniqueUsingHash("1234")? "Unique" : "Not Unique");  
         System.out.println(isUniqueUsingSort("123")? "Unique" : "NotUnique");  
   }  
 }  


Enjoy Coding

Sunday, 20 August 2017

Interesting facts of Java


Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suite various types of platforms. Ex: J2EE for Enterprise Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere.
Java is:
  • Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
  • Platform independent: Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.
  • Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be easy to master.
  • Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.
  • Architectural-neutral: Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence of Java runtime system.
  • Portable: Being architectural-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary which is a POSIX subset.
  • Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.
  • Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications.
  • Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light weight process.
  • High Performance: With the use of Just-In-Time compilers, Java enables high performance.
  • Distributed: Java is designed for the distributed environment of the internet.
  • Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

Enjoy Learning.

Monday, 26 June 2017

WHAT TO CHOOSE for Android Game Development:- canvas or OpenGL or LibGDX or Game Engines!!

Android Game Development - WHAT TO CHOOSE

Canvas or OpenGL or LibGDX or Game Engines!!


Developing games on android is not straight forward. You need to be very specific about what you are going to develop, what are the content of it and what are the requirement for it. Game can be developed from all these but everyone has its own limitation.  

As I am a java and android developer and developed some games in java and android with simple logic(Graphics lib. for java and Canvas for android) I had concluded some points.
  • If graphics are heavy than your game FPS may jitter even though you have proper architecture, but can be solved from accurate and efficient algorithm.
  • Rendering too much graphics can be tedious task.
  • There should be proper architecture of everything.
  • Efficient and best algorithm should be there.
  • Application manageability depends on how you develop it.


Canvas


It is a predefined class in android sdk. Android application can draw things on screen using this class.

java.lang.Object 
   ↳android.graphics.Canvas

means Object class is the parent class of canvas class. This class hold the "draw" calls. It can draw anything like rectangle, circle, bitmap image, etc. To draw anything some basic components is needed which are mentioned below:-
  • Paint object(to give color and style to drawing)
  • Bitmap to hold the pixels
  • Canvas to receive draw calls(drawing on Bitmap)
  • Drawing primitive(path, text, etc.)
How to use it please check android developer documentation.

OpenGL


It is the environment to develop 2D and 3D graphics. It gives the high visual quality and performance. It is cross platform environment.


OpenGl can process image data as well as geometric data.


LibGDX


It is the free game development framework, also it is open source. It is written in Java programming language with some components written in C and C++ to increase the performance. It is the cross platform framework. It can be used desktop application and also for android also.

However this framework is written in java, so the compiled bytecode is language dependent and can be used in any JVM. It main focus was to ease the simplicity and increase the performance.

Game Engine 


It is the tool for fast development of the 2D and 3D games. It is the software framework to develop the mobile and desktop games. The core functionality of the game engine are:-
  • rendering(for 2D and 3D graphics)
  • Physics(collision detection)
  • Sounds
  • Artificial Intelligence
  • Networking
  • Memory management and many more.....
It makes the portability and reusability of the code. There are so many game engines in the market right now, one can choose as per its convenience. Some popular Game Engines are:-
  • UNITY
  • UNREAL
  • RENDERWARE
  • X-RAY

WHAT TO CHOOSE!!


The choice is based on some factors like how much time is available, availability of resources, quality of product and many more. after considering all these points one should choose accordingly.

But my personal advice would be Game Engine as you can do so much in less time and no heavy programming skill is needed. Not because of less programming but the quality of content is far more good and manageability is easy. If one wants to develop the game from basic logic, one can to understand how things happen but if they want to build heavy game with simple libraries it will be surely very difficult. So, it is better to choose game engine.

I personally prefer the UNITY game engine as it is easy to learn and implement. Others are also good but I hadn't used them. Tutorials for all these are available online.


GAME ENGINE would be good option.  


Thursday, 22 June 2017

Log4j

Log4j is a Reliable, Fast and Flexible Logging Framework (APIs) written in Java which is distributed under the Apache Software License. Log4j is highly configurable through external configuration files at runtime. It views the logging process in terms of levels of priorities and offers mechanisms to direct logging information to a great variety of destinations, such as a database, file, console, UNIX Syslog etc.
Log4j has three main components:
  • loggers: Responsible for capturing logging information.
  • appenders : Responsible for publishing logging information to various preferred destinations.
  • layouts: Responsible to format logging information in different styles.
log4j Features:
  • log4j is thread-safe.
  • log4j supports multiple output appenders per logger.
  • log4j supports internationalization.
  • Logging behavior can be set at runtime using a configuration file.
  • log4j is designed to handle Java Exceptions from the start.
  • log4j uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL.
  • The format of the log output can be easily changed by extending the Layout class.
Logging Methods:
Once we obtain an instance of a named logger, we can use several methods of the logger to log messages. The Logger class has the following methods for printing the logging information.
public void debug(Object message)
This method prints messages with the level Level.DEBUG.
public void error(Object message)
This method prints messages with the level Level.ERROR.
public void fatal(Object message);
This method prints messages with the level Level.FATAL.
public void info(Object message);
This method prints messages with the level Level.INFO.
public void warn(Object message);
This method prints messages with the level Level.WARN.
public void trace(Object message);
This method prints messages with the level Level.TRACE.
All the levels are defined in the org.apache.log4j.Level class and any of the above mentioned method can be called as follows:
import org.apache.log4j.Logger;  
 public class LogClass {  
  private static Logger log = Logger.getLogger(LogClass.class);  
  public static void main(String[] args) {  
   log.trace("Trace Message!");  
   log.debug("Debug Message!");  
   log.info("Info Message!");  
   log.warn("Warn Message!");  
   log.error("Error Message!");  
   log.fatal("Fatal Message!");  
  }  
 }  
When you compile and run LogClass program it would generate following result:

 Debug Message!   
 Info Message!   
 Warn Message!   
 Error Message!   
 Fatal Message!  
log4j - Log Formatting:
Apache log4j provides various Layout objects, each of which can format logging data according to various layouts. It is also possible to create a Layout object that formats logging data in an application-specific way
The Layout Types:
The top-level class in the hierarchy is the abstract class org.apache.log4j.Layout. This is the base class for all other Layout classes in the log4j API.
The Layout class is defined as abstract within an application, we never use this class directly; instead, we work with its subclasses which are as follows:
  • DateLayout
  • HTMLLayout
  • PatternLayout.
  • SimpleLayout
  • XMLLayout
log4j - Sample Program:
Following is a simple configuration file created for our example.It has the following information:
  • The level of the root logger is defined as DEBUG and attaches appender named FILE to it.
  • The appender FILE is defined as org.apache.log4j.FileAppender and writes to a file named "log.out" located in the log directory.
  • The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character.
So the content of log4j.properties file would be as follows:
# Define the root logger with appender file  
 log = /usr/home/log4j  
 log4j.rootLogger = DEBUG, FILE  
 # Define the file appender  
 log4j.appender.FILE=org.apache.log4j.FileAppender  
 log4j.appender.FILE.File=${log}/log.out  
 # Define the layout for file appender  
 log4j.appender.FILE.layout=org.apache.log4j.PatternLayout  
 log4j.appender.FILE.layout.conversionPattern=%m%n  
Using log4j in Java Program:
The following Java class is a very simple example that initializes, and then uses, the Log4J logging library for Java applications.
import org.apache.log4j.Logger;  
 import java.io.*;  
 import java.sql.SQLException;  
 import java.util.*;  
 public class log4jExample{  
  /* Get actual class name  to be printed on */  
  static Logger log =  Logger.getLogger(log4jExample.class.getName());  
  public static void main(String[] args) throws IOException,SQLException{  
   log.debug("Hello this is an debug message");  
   log.info("Hello this is an info message");  
  }  
 }  

Enjoy Reading :)

Friday, 16 June 2017

How to get Resolution of android device during runtime

How to get Resolution of android device during runtime


Getting Resolution of the android screen is one of the important aspect when application is to be made for different resolution devices.
So, in order to get the resolution of the device there is predefined library(Display Metrics) in android sdk. You just need to call the method provided by it. The methods are mentioned below.

 DisplayMetrics DM = new DisplayMetrics();  
 getWindowManager().getDefaultDisplay().getMetrics(DM);  

This DM object have the information about no. of pixels in height and width and density of the screen. To get these information Call following method:-

For no. of pixels in length

 DM.heightPixels;  

For no. of pixels in width

 DM.widthPixels;  

For Density of Screen

 DM.densityDpi;  

This information is used frequently in code so it is better to make a wrapper class of this and add some basic functions in it. The custom Wrapper class is defined below.

Wrapper Class for DM object


Firstly you have to pass the DM object to this class's constructor.

 DisplayMetrics DM = new DisplayMetrics();  
 getWindowManager().getDefaultDisplay().getMetrics(DM);  
 ScreenResolution SR = new ScreenResolution(DM);  

Now create the custom class named as ScreenResolution:-

import android.util.DisplayMetrics;
public class ScreenResolution { public static DisplayMetrics dm; public ScreenResolution(DisplayMetrics dm){ this.dm=dm; } public static int getHeight(){ return dm.heightPixels; } public static int getWidth(){ return dm.widthPixels; } public static int getDensity(){ return dm.densityDpi; } public static int percent_of_width(int param){ return ((param*(dm.widthPixels))/100); } public static int percent_of_height(int param){ return ((param*(dm.heightPixels))/100); } }

This class should be placed in custom Package. This class is beneficial in storing and getting the information about the screen's resolution.

ENJOY  DEVELOPING!!

Wednesday, 14 June 2017

ConcurrentHashMap in Java

ConcurrentHashMap

ConcurrentHashMap in Java is introduced as an alternative of Hashtable in Java 1.5 as part of Java concurrency package.  Prior to Java 1.5 if you need a Map implementation, which can be safely used in a concurrent and multi-threaded Java program, then you only have Hashtable or synchronized Map because HashMap is not thread-safe.
With ConcurrentHashMap, not only it can be safely used in concurrent multi-threaded environment but also provides better performance over Hashtable and synchronizedMap. ConcurrentHashMap performs better than earlier two because it only locks a portion of Map, instead of whole Map, which is the case with Hashtable and synchronized Map. ConcurrentHashMap allows concurred read operations and same time, maintains integrity by synchronizing write operations.

How ConcurrentHashMap is implemented in Java

ConcurrentHashMap provided all functions supported by Hashtable with additional feature called "concurrency level", which allows ConcurrentHashMap to partition Map. ConcurrentHashMap allows multiple readers to read concurrently without any blocking. This is achieved by partitioning Map into different parts based on concurrency level and locking only a portion of Map during updates. Default concurrency level is 16. This means, 16 thread can operate on Map simultaneously, until they are operating on different part of Map. This makes ConcurrentHashMap high performance despite keeping thread-safety intact. Though, it comes with warning. Since update operations like put(), remove(), putAll() or clear() is not synchronized, concurrent retrieval may not reflect most recent change on Map.
Another important point to remember is iteration over CHM, Iterator returned by keySet of ConcurrentHashMap are weekly consistent and they only reflect state of ConcurrentHashMap and certain point and may not reflect any recent change. Iterator of ConcurrentHashMap's keySet area also fail-safe and doesn’t throw ConcurrentModificationExceptoin.

ConcurrentHashMap putifAbsent example in Java

Many times we need to insert entry into Map, if it’s not present already, and we wrote following kind of code:

synchronized(map){  
  if (map.get(key) == null){  
    return map.put(key, value);  
  } else{  
    return map.get(key);  
  }  
 }  

Though this code will work fine in HashMap and Hashtable, This won't work in ConcurrentHashMap; because, during put operation whole map is not locked, and while one thread is putting value, other thread's get() call can still return null which result in one thread overriding value inserted by other thread. Of course, you can wrap whole code in synchronized block and make it thread-safe but that will only make your code single threaded. ConcurrentHashMap provides putIfAbsent(key, value) which does same thing but atomically and thus eliminates above race condition.
Eg:
public class ConcurrentHashMapTest implements Runnable {  
     private String name;  
     private static Map<String,String> conpage=new ConcurrentHashMap<String,String>();  
     ConcurrentHashMapTest(String name){  
        conpage.put("1","A");  
        conpage.put("2","B");  
        conpage.put("3","C");  
        this.name=name;  
     }  
     public void run() {  
        try{  
            Iterator<String> it = conpage.keySet().iterator();  
            while(it.hasNext()){  
               String key=it.next();  
               conpage.put("A"+key, "A"+key);  
            }  
            System.out.println(name +" completed.");  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
     }  
     public static void main(String[] args) {  
        ExecutorService executor= Executors.newCachedThreadPool();  
        executor.execute(new ConcurrentHashMapTest("Thread one"));  
        Iterator<String> itt = conpage.keySet().iterator();  
        while(itt.hasNext()){  
            String key=itt.next();  
            System.out.println(conpage.get(key));  
        }  
        executor.execute(new ConcurrentHashMapTest("Thread two"));  
        Iterator<String> it = conpage.keySet().iterator();  
        while(it.hasNext()){  
            String key=it.next();  
            System.out.println(conpage.get(key));  
        }  
        executor.shutdownNow();  
     }     
 }  

Output-  
 A  
 C  
 B  
 Thread one completed.  
 A  
 A2  
 A1  
 A3  
 C  
 B  
 Thread two completed.  

When to use ConcurrentHashMap in Java

  • ConcurrentHashMap is best suited when you have multiple readers and few writers. If writers outnumber reader, or writer is equal to reader, than performance of ConcurrentHashMap effectively reduces to synchronized map or Hashtable.
  • ConcurrentHashMap is a good choice for caches, which can be initialized during application start up and later accessed my many request processing threads.
  • For those who have seen the green-box load jobs written in SpringBatch, many of the one-time populated Maps in beforeJob, whch are always read alone, are all ConcurrentHashMap ‘s.

Enjoy Learning :)

Eclipse and its Features

We work on Eclipse every day, but still we are not aware of all the powerful features of Eclipse. It provides a lot of shortcuts and other features which can help us in coding, debugging and other tasks, eventually delivering the bug free code in a lot lesser time.
Some of them are mentioned below and yet there are a lot more J 
Content Assist, Quick Fix and Class Navigation
Content assist
The content assistant allows you to get input help in an editor. It can be invoked by pressing CTRLSpace For example type syso in the editor of a Java source file and then press CTRLSpace. This will replace syso with System.out.println(""). If you have a reference to an object, for example the object person of the type Person and need to see it's methods, type person. and press CTRL+Space.
Quick Fix
Whenever Eclipse detects a problem, it will underline the problematic text in the editor. Select the underlined text and press CTRL1 to see proposals how to solve this problem. For example type myBoolean = true; If myBoolean is not yet defined, Eclipse will highlight it as an error. Select the variable and press CTRL1, Eclipse will suggest creating a field or local variable.
Quick Fix is extremely powerful. It allows you to create new local variables and fields as well as new methods and new classes. I can put try-catch statements around your exceptions. It can assign a statement to a variable and much more.
Opening a class
You can navigate between the classes in your project via the "Package Explorer" View. In addition you can open any class via positioning the cursor on the class in an editor and pressing F3. Alternatively, you can press CTRLShiftT. This will show a dialog in which you can enter the class name to open it.
Eclipse Shortcuts
Eclipse provides a lot of shortcuts to work efficiently with the IDE.
Table 1.  Navigation

Shortcut
Description
Ctrl + 2 + L
Assign statement to new local variable
Ctrl + 2 + F
Assign statement to new field
Table 4. Coding

Shortcut
Description
ALT + SHIFT + R
Rename
CTRL+2, R
Rename locally (in file), faster then ALT + SHIFT + R
ALT + SHIFT + T
Opens the quick refactoring menu
Table 6.  Handling the editor

Command
Description
F5
Goes to the next step in your program. If the next step is a method / function this command will jump into the associated code.
F6
F6 will step over the call, i.e. it will call a method / function without entering the associated code.
F7
F7 will go to the caller of the method/ function. This will leave the current code and go to the calling code.
F8
Use F8 to go to the next breakpoint. If no further breakpoint is encountered the program will run normally.

More Debugging Tips!!
  • If you want to temporary de-activate all your breakpoints you can press the button "Skip all breakpoints". This button is visible, if you select the "Breakpoints" tab. If you press this button again, your breakpoints will be reactivated.
    • After setting a breakpoint you can select the properties of the breakpoint, via right-click > Breakpoint Properties. You can define a condition that restricts when the breakpoint will become active.
    • watchpoint is a breakpoint set on a field. The debugger will stop whenever that field is read or changed.
    • You can set a watchpoint by double-clicking on the left margin, next to the field declaration. In the properties of a watchpoint you can define if the execution should stop during read access (Field Access) and during write access (Field Modification).
    • You can also set breakpoints which are triggered when exceptioins are thrown. To define an exception breakpoint click on the "Add Java Exception Breakpoint" icon in the "Breakpoints" View toolbar.
    • A method breakpoint is defined by double-clicking in the left margin of the editor next to the method header. You can define if you want to stop the program before entering or after leaving the method.
    • A Class Load Breakpoint will stop when the class is loaded. To set a class load breakpoint, right-click on a class in the Outline View and choose "Toggle Class Load Breakpoint".
For every breakpoint you can define a hit count in it's properties. The application is stopped once the breakpoint is reached the number of times defined in the hit count.

Templates
If you have to frequently type the same code / part of the document, you can create templates which can be activated via autocomplete (Ctrl + Space).
For example, assume that you are frequently creating public void name(){} methods. You could define a template which creates the method body for you.
To create a template for this, select the menu Window > Preferences > Java > Editor > Templates.



Press New. Create the template shown in the following screenshot.


cursor indicates that the cursor should be placed at this position after applying the template.
In this example the name "npm" is your keyword. Now every time you type "npm" in the Java editor and press CTRL+Space the system will allow you to replace your keyword with your template. 
 Automatic placement of semicolon
Eclipse can make typing more efficient by placing semicolons at the correct position in your source code.
In the Preference setting select Java > Editor > Typing. In the section "Automatically insert at correct position”, enable the "Semicolons" checkbox. You can now type a semicolon in the middle of your code and Eclipse will position it at the end of the current statement.



Enjoy Learning :)

Wednesday, 24 May 2017

Overview of HTTP Request Methods

HTTP defines methods (sometimes referred to as verbs) to indicate the desired action to be performed on the identified resource. What this resource represents, whether pre-existing data or data that is generated dynamically, depends on the implementation of the server. Often, the resource corresponds to a file or the output of an executable residing on the server.

The HTTP/1.0 specification section  defined the GET, POST and HEAD methods and the HTTP/1.1 specification section  added 5 new methods: OPTIONS, PUT, DELETE, TRACE and CONNECT. By being specified in these documents their semantics are well known and can be depended upon. Any client can use any method and the server can be configured to support any combination of methods. If a method is unknown to an intermediate it will be treated as an unsafe and non-idempotent method

GET
Requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect.
HEAD
Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.
POST
Requests that the server accept the entity enclosed in the request as a new subordinate of the web resource identified by the URI. The data POSTed might be, as examples, an annotation for existing resources; a message for a bulletin board, newsgroup, mailing list, or comment thread; a block of data that is the result of submitting a web form to a data-handling process; or an item to add to a database
PUT
Requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified; if the URI does not point to an existing resource, then the server can create the resource with that URI.
DELETE
Deletes the specified resource.
TRACE
Echoes back the received request so that a client can see what (if any) changes or additions have been made by intermediate servers.
OPTIONS
Returns the HTTP methods that the server supports for specified URL. This can be used to check the functionality of a web server by requesting '*' instead of a specific resource.
CONNECT
Converts the request connection to a transparent TCP/IP tunnel, usually to facilitate SSL-encrypted communication (HTTPS) through an unencrypted HTTP proxy.[14][15]
PATCH
Is used to apply partial modifications to a resource.
HTTP servers are required to implement at least the GET and HEAD methods and, whenever possible, also the OPTIONS method.

Safe methods
Implementers should be aware that the software represents the user in their interactions over the Internet, and should be careful to allow the user to be aware of any actions they might take which may have an unexpected significance to themselves or others.
In particular, the convention has been established that the GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval. These methods ought to be considered "safe". This allows user agents to represent other methods, such as POST, PUT and DELETE, in a special way, so that the user is made aware of the fact that a possibly unsafe action is being requested.
Naturally, it is not possible to ensure that the server does not generate side-effects as a result of performing a GET request; in fact, some dynamic resources consider that a feature. The important distinction here is that the user did not request the side-effects, so therefore cannot be held accountable for them.

Idempotent methods
Methods can also have the property of "idempotence" in that (aside from error or expiration issues) the side-effects of N > 0 identical requests is the same as for a single request. The methods GET, HEAD, PUT and DELETE share this property. Also, the methods OPTIONS and TRACE SHOULD NOT have side effects, and so are inherently idempotent.
However, it is possible that a sequence of several requests is non- idempotent, even if all of the methods executed in that sequence are idempotent. (A sequence is idempotent if a single execution of the entire sequence always yields a result that is not changed by a reexecution of all, or part, of that sequence.) For example, a sequence is non-idempotent if its result depends on a value that is later modified in the same sequence.
A sequence that never has side effects is idempotent, by definition (provided that no concurrent operations are being executed on the same set of resources).

Persistent connections
In HTTP/0.9 and 1.0, the connection is closed after a single request/response pair. In HTTP/1.1 a keep-alive-mechanism was introduced, where a connection could be reused for more than one request. Such persistent connections reduce request latency perceptibly, because the client does not need to re-negotiate the TCP connection after the first request has been sent. Another positive side effect is that in general the connection becomes faster with time due to TCP's slow-start-mechanism.
Version 1.1 of the protocol also made bandwidth optimization improvements to HTTP/1.0. For example, HTTP/1.1 introduced chunked transfer encoding to allow content on persistent connections to be streamed rather than buffered. HTTP pipelining further reduces lag time, allowing clients to send multiple requests before waiting for each response. Another improvement to the protocol was byte serving, where a server transmits just the portion of a resource explicitly requested by a client.

Enjoy Learning.