Showing posts with label java tutorial. Show all posts
Showing posts with label java tutorial. Show all posts

Monday, October 5, 2020

How to Learn Java 2021 | What are the skills required to become Java Developer 2021

 In this post you will now what are the skills required to become a java developer 2021 based on their experience. Java has been a leading programming language In IT. It is widely used for developing web applications, enterprise applications, cloud computing applications, Machine learning environment and IoT . Java is most popular choice writing android apps. 


Fresher or Beginner

Core Java

Advanced Java Servlets and JSP(Good to have)

Basic Knowledge Of spring framework

Database Skills like SQL , oracle 

Frontend Tech like HTML,CSS and JS

Basic knowledge on Linux and windows environments



For 1 to 3 Years Experience Java Developer

Core Java

Advanced Java Servlets and JSP

Web framework like Spring and Springboot framework

Hibernate Framework

Database skills: SQL, ORACLE

Micro services

Frontend Tech like HTML, CSS and JS

Web services like SOAP/REST(Intermediately) 

Java Build Tool: Maven, ant

Any web or application server like Tomcat, web logic

• Comfortable with Linux/Unix and Windows environments.



For 3 to 7 Years Experience Java Developer:

Core Java

Advanced Java Servlets and JSP

Web framework like Spring and Springboot framework

Hibernate Framework

Database skills: SQL, ORACLE

Microservices

Front-end Tech like HTML, CSS and JS

Web services like SOAP/REST

Design Patterns 

Java Build Tool: Maven, ant, Gradle 

Any one JS framework( React, angular,JQuery)

JUNIT( Testing framework)

Any application server like weblogic , JBOSS, Tomcat and web sphere

Software methodology like agile

Any automation Testing tool like Selenium

Any Cloud Services Exp like AWS , azure or GCP

Basic Network  related skills.

Comfortable with Linux/Unix and Windows environments.



For 7 to 15 Years  Experience Java Developer:

The above Skills and the following skills:

• Strong Experience with relational databases, SQL, ORACLE . Experience with PostgresSQL 

• Experience working with Docker

• Familiar with security, authentication , authorization (Oauth2.0) technologies

• Comfortable with Linux/Unix and Windows environments.

• Software development and engineering skills on large-scale, mission-critical infrastructure applications is a plus.

• Demonstrated ability to develop tests at the unit and component level for either frontend or backend.

• Exp with Agile SCRUM development methodologies

Experience with SaaS, container development strongly desired.


• Experience with distributed and/or big data systems 

• Experience with concurrency issues in multi-threaded programs

• Experience working with Kubernetes

• Experience working with jenkins

• Should have good debugging skills, project set up etc..

• Project Management skills(nice to have PMP Certification)

• Nice to certifications like OCAJP ,Spring profession certification, aws solution architect, scrum master certification, pmp certification









Saturday, June 29, 2019

What Features of Java is Used very often By Experienced Programmers?

In this post you will know what are the features of java is used by experienced Programmers but not junior developers. A very simple test to differentiate between an experienced programmer and a newbie is to ask the two to concatenate about a 1000 unidentical strings.

A newbie programmer would do it as simply as

public String computeResult(String[] arr) {
    String result = "";
    for(int i = 0; i < arr.length; i++){
        result = result + arr[i];
    }
    return result;
}

The problem with the above code snippet is that the plus operator when used to concatenate strings has a major overhead that compromises to the performance.

Although the use of the "+" operator is substituted with StringBuilder which is further converted to a String during compile time, this sequence of events would be taking place repeatedly within the loop and the code would be creating and then discarding an intermediate String object repeatedly.

Now, if an experienced programmer was asked, he/she would realize that we are dealing with a lot of strings and would do the same task as -

public String computeResult(String[] arr) {
    StringBuilder sb = new StringBuilder();
    for(String temp : arr)
        sb.append(temp);
    return sb.toString();
}

Of course its possible that the programmer might divide the array in two parts or more and then have multiple threads each computing its own concatenated string; further there might be a final merge which would connect all such strings but that's not the point.

Coming back to the question, using StringBuilder to concatenate Strings can be a feature usually used by experienced programmers.

2nd Example:

Beginner:

ArrayList<String> stringList = new ArrayList<String>();

Experienced developer:

List<String> strings = new ArrayList<>(); //Java7+

There is also the case of writing interfaces. This is a bit more complicated than to write a concrete class, since there is an extra level of abstraction. Some new developers might find this cumbersome and avoid it it not necessary. However, interfaces have great advantages in maintaining contracts.

public interface Car {
    void deaccelerate(BreakType type); // HARD, PANIC, SOFT, etc, ...
    void accelerate(float acceleration); // Newton Meter?
    void changeGear(Gear gear) //ONE, TWO, ...
}

public class CarFactory {
    public CarFactory(){}

    public Car getCar(CarType type) {
        //Implement
    }
}

class Ferrari implements Car {
    // Implementation
}

class Fiat implements Car {
    //Implementation
}

So basically you can only access the internal implementations of the car unless you use reflection. There is no way that someone will be able to use anything else than you allow them to. The only way for the users of the Car class will be able to create a Car is by using the CarFactory. Then the user will get a Car defined in the CarType enum.

A possible issue is that all new Cars need to be added to the CarType struct, so it is not possible to do own extensions. However, Car is just an example that I use and is easy to come up with. This kind of implementations is normally done for things that should not be meddled with outside of the API that is used.

Tuesday, June 18, 2019

How do perform a NULL check for String in Java

In this post you will know how to check if String is null or empty in java. There are 4 ways to check if String is null or empty in java. Each solution has their pros and cons and a special use case e.g. first solution can only be used from JDK7 on wards, second solution is the fastest way to check string is empty and third solution should be used if your string contains whites paces. Fourth solution is with Apache Commons Lang, one simple call does it all.

Solution1:- 

Using isEmpty() method:-

This is the most readable way to check both whether the string is null or empty. you can see the below code,
if(string!=null && !string.isEmpty()){

System.out.println(“String is not null and not empty”);

}

A couple of things you need to remember about this solutions that is

the same order of check should be maintained because isEmpty() is a non-static method if you called it on null reference then Null Pointer Exception(NPE) will be thrown.
Second thing you should keep in mind is that isEmpty() method should be used from JDK7 onwards, as I mentioned earlier.


2nd solution - 

Using length() function:-

This is the universal solution and works in all versions of Java, from JDK 1.0 to Java8. I highly recommend this method because of portability advantage it provides. It is also the fastest way to check if String is empty in Java or not.
if(string!=null && string.length()>0){

System.out.println(“String is not null and not empty”);

}
- One thing which is very important here is that if String contains just whitespace then this solution will not consider it as empty String. The emptiness check will fail because string.length() will return a non-zero value. If you are considering the String with only whitespaces as empty then use the trim() method as shown in the third example.

3rd solution - 

Using trim() method:-

This is the third way to check whether String is empty or not. This solution first calls the trim() method on the String object to remove leading and trailing white spaces.
if(string!=null && string.trim.length()>0){

System.out.println(“String is not null and not empty”);

}
- You can use this solution if your program doesn't consider a String with only white-space as a non-empty. If you load data from the database or stored data into the database it's better to trim() them before using to avoid pesky issue due to whitespaces.

4th Solution - 

Using isBlank() method of Apache Commons Lang

The StringUtils.isBlank(String) static method performs three checks in single method. check a String to ensure it is not null, not empty, and not white space only. In your project if you are using Apache commons Lang jar then you can definitely use this method.
import org.apache.commons.lang.StringUtils;

public boolean isNullOrEmpty(String string){

return StringUtils.isBlank(string);

}

Friday, June 14, 2019

Difference Between Object Code and Byte Code

In this post you will learn one of the famous interview question for fresher that is can you tell me the difference between Object code and Byte code with examples. First Let me define

object code: 

It is an compiled code generated from c/c++ programs. Operating System is participated in generating objective code.



Disadvantage:

The object code which is generated from one platform can not be executed on
other platform, The code c and c++ languages which are generating objective code are platform dependent .



Byte code:

This code is also a compiled code generated from java programs.

Operating System is not participated in generating byte code because of this reason byte code is an platform independent code.

Advantage:

The byte code which is generated from one platform can be executed on all the platforms in real time.

Examples:
irctc.com
gmail
bankof baroda...

Tuesday, June 11, 2019

Java Program to perform Calculator Operations

In this post you will learn Basic calculator operations program by using Java. Basic calculator Operations means additions,subtractions,multiplication and division. To implement this operation i am using Java programming Language. The following code will help to implement calculator operations.




package seleniumsession1;

import java.util.Scanner;

public class CalculatorDemo {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("enter two numbers");
double first=sc.nextDouble();
double second=sc.nextDouble();
System.out.println("enter an operator(+,-,*,/):");
char ch=sc.next().charAt(0);
double result;

switch(ch) {
case '+':
      result=first+second;
      break;
case '-':
      result=first-second;
      break;
case '*':
      result=first*second;
      break;
case '/':
      result=first/second;
      break;
   default:
           System.out.println("incorrect operator");
           return;
}
System.out.printf("%.1f %c %.1f = %.1f", first, ch, second, result);


}

}

Output:
Enter two numbers:

100  200

enter any operator:
+
100.0+200.0=300.0

Sunday, June 9, 2019

JVM Architecture in Java

In this post you will learn what is JVM and architecture of JVM. It is an abstract machine which provides run time environment in which java byte code can be executed. JVM was designed as an interpreter for byte code. JVM is the heart of entire Java Program Execution process.



Let's understand the internal architecture of JVM:


It contains class loader , memory area , execution engine 


1)class loader :


class loader is a subsystem of JVM that is used to load class files. It loads the .class file into memory.Then it verifies whether all byte code instructions are proper or not. If it finds any suspicious,then execution is rejected immediately. If instructions are proper then it allocates necessary memory to execute the program.


2)class area:     


class area is also called method area. It is a memory block,which stores the class code,code of the variables and code of the methods in the java program.


3) Heap :  


It is the run time data area in which objects are allocated that means where objects are created. Whenever JVM loads a class,a method and a heap area are immediately created in it.


4) stack : 


Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation and return.Each thread has a private JVM stack, created at the same time as thread.A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.


5) Program Counter :  


PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed. In other words, PC contains memory address of the instructions of the methods.


6)Native method stack: 


It contains all the native methods used in the application. Native methods are nothing but C/C++ functions. To execute native methods,generally native method libraries are required. These header files are located and connected to JVM by a program called Native method interface.




7) Execution Engine : 


Execution Engine Contains interpreter and JIT compiler


Interpreter:  It is used to converting the byte code instructions into machine code so that the processor will execute them. Most of the JVM implementations use both the interpreter and JIT compiler simultaneously to covert byte code .


Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term ?compiler? refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

Saturday, June 8, 2019

Object class methods with examples in Java

The most common general methods which are applicable on any object are defined in object class.This class provides methods to compare objects,to covert an object into a string, to notify threads regarding the availability of an object.

Object class defines the fallowing methods:

1) equals(): 

This method is used to compare two object for equality and if they are equal,it returns true otherwise false.Let us see how to compare two objects by using equals() method of Object class.

Generally Object class equals() methods compares the reference of two objects. If both object refer to same object then it gives true otherwise false. But based on our requirement it is recommended to override equals() method for content comparison. 

Example:

class EqualsDemo
{
public static void main(String args[])
{
String s1="HI";
String s2="HI";
String s3="welcome to java";
System.out.println(s1 + " equals " + s2 + " -> " +s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +s1.equals(s3));
}
}


Output:






In the above program Object class equals() methods has executed which is meant for reference comparison. But base on our requirement it is recommended to override equals() method for content comparison.

Example:


class Employee
{
String name;
int rollno;
Employee(String name,int rollno)
{
this.name = name;
this.rollno = rollno;
}
public boolean equals(Object obj)
{
try
{
String name1 = this.name;
int rollno1 = this.rollno;
Employee e2 = (Employee)obj;
String name2 = e2.name;
int rollno2 = e2.rollno;
if(name1.equals(name2) && rollno1 == rollno2)
{
return true;
}
else
{
return false;
}
}
catch (ClassCastException c)
{
return false;
}
catch (NullPointerException e)
{
return false;
}
}
public static void main(String arg[])
{
Employee e1 = new Employee ("pavan", 1);
Employee e2 = new Employee ("mahesh", 2);
Employee e3 = new Employee ("Eeswar", 3);
System.out.println(e1.equals(e2));
System.out.println(e2.equals(e3));
System.out.println(e1.equals(null));
}
}


Output:






2) toString():

This method returns a string representation of an object. 


Syntax:

public String toString()
{
return getClass.getName();
}

Example:


class Employee

{
String name;
int rollno;
Employee(String name,int rollno)
{
this.name = name;
this.rollno = rollno;
}

public static void main(String args[])
{
Employee e1=new Employee("nagaraju",1);
Employee e2=new Employee("prasad",2);
System.out.prinltn(e1);
System.out.prinltn(e2);
}
}
Output:






Whenever we are passing object reference as argument to System.out.println() internally JVM will call toString() on that object. If we are not providing toString() then Object class toString() will be executed which is implemented as fallows:

public String toString()

{
return getClass.getName()+'@'+Integer.toHexString(hashcode);
}
Based on our requirement to provide our own String representation we have to override toString(). Let us rewrite the above program by overriding toString() method


Example:


class Employee

{
String name;
int rollno;
Employee(String name,int rollno)
{
this.name = name;
this.rollno = rollno;
}
public String toString()
{
return name+"-------"+rollno;
}

public static void main(String args[])

{
Employee e1=new Employee("nagaraju",1);
Employee e2=new Employee("prasad",2);
System.out.println(e1);
System.out.println(e2);
}

}

Output:






3) getClass():

This method returns the runtime class of an object. 



4) hashCode():

This method returns a hash code value of the object. The hash code of an object just represents a random number which can be used by JVM while saving objects into hash tables,HashSet and HashMap.

hashCode() of an Object class implemented to return hashCode based on address of an object,but based on our requirement we can override hashCode() to generate our own numbers as hashCode.

Example:

class Demo

{
int a;
Demo(int a)
{
this.a = a;
}
public int hashCode()
{
return a;
}
public static void main(String arg[])
{
Demo d1 = new Demo(10);
Demo d2 = new Demo(20);
System.out.println(d1); 
System.out.println(d2);
}

}
Output:





Observe above program output JVM automated generated numbers displayed. So to get our own number we have to override hashCode(). Let us Rewrite the above program as fallows:

Example:

class Demo
{
int a;
Demo(int a)
{
this.a = a;
}
public int hashCode()
{
return a;
}
public String toString()
{
return a + "";
}
public static void main(String arg[])
{
Demo d1 = new Demo(10);
Demo d2 = new Demo(20);
System.out.println(d1); 
System.out.println(d2);
}
}

Output:





5) clone():

The process of creating exactly duplicate object is called cloning. 


Example:

class Demo implements Cloneable
{
int x = 10;
int y = 20;
public static void main(String arg[])throws CloneNotSupportedException
{
Demo d1 = new Demo();
Demo d2 = (Demo)d1.clone();
d1.x = 100;
d1.y = 200;
System.out.println(d2.x+"----"+d2.y); 
}
}

Output:





6) finalize():

This method is called by garbage collector on an object when garbage collection determine that there are no more reference to the object.

7) notify():

This method is used to wake up single thread that is waiting on the object's monitor.

8) notifyAll():

This method is used to wake up all the threads that are waiting on the object's monitor.

9) wait():

This method causes to waits to be notified by another thread of a change in this object.

I hope you enjoy this post and Let me know your comments on this post and share this to your friends,keep follow me for latest updates.

Friday, March 1, 2019

Where is java used?

In this post i am sharing where we used java and list of companies used java programming  across world. Java is the king of all the programming languages. We can see the application of Java everywhere, like in our mobile phones, desktops, websites. Java is majorly used for Application Development.

Let’s see some other Java applications:

Desktop application
Web application
Android application
Big Data
Cloud Computing
Robotics
Enterprise application
Scientific Application
Research and development
Retailing and e-commerce
Operating system
Cryptography
Banking
Computer games
Videogames
Web & Application servers
Smart Codes
Embedded system
Real-time software

List of Companies using Java Programming Languages

Today, Java is used almost in every company. According to research more than 64,000 companies using Java in the USA.

Big companies in the world

Airbnb
Uber
eBay
Pinterest
Groupon
Spotify
Pandora
Square



Big companies in India

Infosys
TCS
Wipro
HCL
Tech
Jaboong
Myntra
Flipkart
Trivago
Ibibo
Tripadvisor

Biggest Internet companies

Google
Accenture

Hardware companies

Intel
Symantec
Philips
Thomson
T-Mobile
Huge Product Companies
Thumbtack
Evernote
Klout
BetterCloud
Yelp
Okta
Stack
Any company, which has 1 million to 10 million revenue is using Java for the time being.

Thursday, December 13, 2018

Difference Between checked Exception and Unchecked Exception in Java

In this post you will learn what is checked and unchecked Exceptions and difference between them. The following are the differences between them.

Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword. 

Example: FileNotFoundException, EndOfFileException etc.

So the compiler at compile time will check if a certain method is throwing any of the checked exceptions or not,if yes it will check whether the method is handling that exception either with “Try&Catch” or “throws”,if in case the method is not providing the handling code then compiler will throw error saying “Unreported Exception”

For example

import java.io.*
class Example
{
public static void main(String[] args)
 {
PrintWriter pw=new PrintWriter("xyz.txt"); //creating a new printwriter object to write in a file named "xyz.txt"
pw.println("Hello World");
 } }

The above snippet is supposed to print “Hello World” in file named “xyz.txt”

There may be a chance of file “xyz.txt” is not present in specified directory,so the compiler will check if any handling code is provided in case file is not present

In above snippet handling code is not provided either with “Try&Catch” or “throws” so the compiler will throw error

The same example with some modification:

import java.io.*
Class Example
{
public static void main(String[] args) throws FileNotFoundException
 {
PrintWriter pw=new PrintWriter("xyz.txt"); //creating a new printwriter object to write in a file named "xyz.txt"
pw.println("Hello World");
}}
In this example handling code is provided with “throws” so compiler will not throw any error.



Unchecked Exceptions:

There are some exceptions which do not occur regularly in a program,and compiler will not check for those exceptions,these kind of exceptions are called Unchecked Exceptions

Example: ArithmeticException, NullPointerException etc

For example:

class Example{
public static void main(String[] args){
System.out.println(10/0); //Arithmetic Exception
}
} 
The above program should throw “Arithmetic Exception” as division with “0” is not allowed

In this case the program compiles fine because compiler will not check for “Unchecked Exceptions” but the program will throw error at “Run Time” as division with “0” is illegal.

Saturday, December 8, 2018

How to reduce Execution time of Java Program?

In this post you  will learn how to reduce execution time of Java Program. The following are the some of the best practices for java programmer. 

1.Always return empty Collections and Arrays instead of null

Whenever your method is returning a collection element or an array, always make sure you return empty array/collection and not null. This will save a lot of if else testing for null elements. 
2. Avoid creating unnecessary objects and always prefer to do Lazy Initialization:

Object creation in Java is one of the most expensive operation in terms of memory utilization and performance impact. It is thus advisable to create or initialize an object only when it is required in the code.
-------------------------------------------------------------------
public class ABC {

    private List abc;
     
    public List getABC() {
         
        if(null == abc) {
            abc = new ArrayList();
        }
        return abc;
    }
}
----------------------------------------------------------------------------
3.Always try to minimize Mutability of a class:

Making a class immutable is to make it unmodified. The information the class preserve will stay as it is through out the lifetime of the class. Immutable classes are simple, they are easy to manage. They are thread safe. They makes great building blocks for other objects.
However creating immutable objects can hit performance of an app. So always choose wisely if you want your class to be immutable or not. Always try to make a small class with less fields immutable.To make a class immutable you can define its all constructors private and then create a public static method to initialize and object and return it.





4.Try to use standard library instead of writing your own from scratch

Writing code is fun. But it is very advisable to use an existing standard library which is already tested, debugged and used by others. This not only improves the efficiency of programmer but also reduces chances of adding new bugs in your code. Also using a standard library makes code readable and maintainable.

5.Wherever possible try to use Primitive types instead of Wrapper classes

Wrapper classes are great. But at same time they are slow. Primitive types are just values, whereas Wrapper classes are stores information about complete class.

6.Use Strings carefully.

Always carefully use Strings in your code. A simple concatenation of strings can reduce performance of program. For example if we concatenate strings using + operator in a for loop then every time + is used, it creates a new String object. This will affect both memory usage and performance time.

7 Algorithms Implementation
This is what you have to work on your own. There is one quote which is rarely false: "There is always a better algorithm for this task." Recursion makes your program very very slow, you can use recurrence relations to solve problems of recursion if you can't do it by some other way. Learn DP, and number theory the hard way, because for a mathematical question, you can make program fast using number theory tricks and for string/text type of questions DP gives memoized solutions.

How to Execute a Java Program?

In this post you will understand how to execute a java program in step by step. The following are the step by step process to execution a Java Program.

  1. Whenever, a program is written in JAVA, the javac compiles it.
  2. The result of the JAVA compiler is the .class file or the bytecode and not the machine native code (unlike C compiler).
  3. The bytecode generated is a non-executable code and needs an interpreter to execute on a machine. This interpreter is the JVM and thus the Bytecode is executed by the JVM.
  4. And finally program runs to give the desired output.

Java program execution follows 5 majors steps:

Editor
Compile
Load
Verify
and Execute

1. Editor - Here the programmer uses a simple editor or a notepad application to write the java program and in the end give it a .java extension

2. Compile - In this step the programmer gives the javac command and the .java files are converted into bytecode which is the language understood by the java virtual machine (and this is what makes java platform independent language). Any compile time errors are raised at this step

3. Load - The program is then loaded into memory. This is done by the class loader which takes the .class files containing the bytecode and stores it in the memory. The .class file can be loaded from your hard disk or from the network as well

4. Verify - the bytecode verifies checks if the bytecode loaded are valid and do not breach java's security restrictions

5. Execute - The JVM interprets the program one bytecode at a time and runs the program

Best Unknown features of Java

In this post you will learn some of the unknown features of Java.Java is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language.
Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in every nook and corner.

The following are the few unknown features of Java:

1. Stamped Locks

Multi-threaded code has long been the bane of server developers (just ask Oracle Java Language Architect and concurrency guru Brian Goetz). Over time complex idioms were added to the core Java libraries to help minimize thread waits when accessing shared resources. One of these is the classic ReadWriteLock that lets you divide code into sections that need to be mutually exclusive (writers), and sections that don’t (readers).

On paper this sounds great. The problem is that the ReadWriteLock can be super slow(up to 10x), which kind of defeats its purpose. Java 8 introduces a new ReadWrite lock – called StampedLock. The good news here is that this guy is seriously fast. The bad news is that it’s more complicated to use and lugs around more state. It’s also not reentrant, which means a thread can have the dubious pleasure of deadlocking against itself.

StampedLock has an "optimistic" mode that issues a stamp that is returned by each locking operation to serve as a sort of admission ticket; each unlock operation needs to be passed its correlating stamp. Any thread that happens to acquire a write lock while a reader was holding an optimistic lock, will cause the optimistic unlock to be invalidated (the stamp is no longer valid). At that point the application can start all over, perhaps with a pessimistic lock (also implemented in StampedLock.) Managing that is up to you, and one stamp cannot be used to unlock another – so be super careful.

Let’s see this lock in action-

long stamp = lock.tryOptimisticRead(); // non blocking path - super fast
work(); // we're hoping no writing will go on in the meanwhile
if (lock.validate(stamp)){
       //success! no contention with a writer thread 
}
else {
       //another thread must have acquired a write lock in the meanwhile, changing the stamp. 
       //bummer - let's downgrade to a heavier read lock

            stamp = lock.readLock(); //this is a traditional blocking read lock 
       try {
                 //no writing happening now
                 work();

       }
       finally {
            lock.unlock(stamp); // release using the correlating stamp
       }
}

2. Concurrent Adders

Another beautiful addition to Java 8, meant specifically for code running at scale, is the concurrent “Adders”. One of the most basic concurrency patterns is reading and writing the value of a numeric counter. As such, there are many ways in which you can do this today, but none so efficient or elegant as what Java 8 has to offer.

Up until now this was done using Atomics, which used a direct CPU compare and swap (CAS) instruction (via the sun.misc.Unsafe class) to try and set the value of a counter. The problem was that when a CAS failed due to contention, the AtomicInteger would spin, continually retrying the CAS in an infinite loop until it succeeded. At high levels of contention this could prove to be pretty slow.

Enter Java 8’s LongAdders. This set of classes provides a convenient way to concurrently read and write numeric values at scale. Usage is super simple. Just instantiate a new LongAdder and use its add() and intValue() methods to increase and sample the counter.

The difference between this and the old Atomics is that here, when a CAS fails due to contention, instead of spinning the CPU, the Adder will store the delta in an internal cell object allocated for that thread. It will then add this value along with any other pending cells to the result of intValue(). This reduces the need to go back and CAS or block other threads.

If you’re asking yourself when should I prefer to use concurrent Adders over Atomics to manage counters? The simple answer is – always.

3. Parallel Sorting

Just as concurrent Adders speed up counting, Java 8 delivers a concise way to speed up sorting. The recipe is pretty simple. Instead of -

Array.sort(myArray);

You can now use –
Arrays.parallelSort(myArray);

This will automatically break up the target collection into several parts, which will be sorted independently across a number of cores and then grouped back together. The only caveat here is that when called in highly multi-threaded environments, such as a busy web container, the benefits of this approach will begin to diminish (by more than 90%) due to the cost of increased CPU context switches.

4. Switching to the new Date API

Java 8 introduces a complete new date-time API. You kind of know it’s about time when most of the methods of the current one are marked as deprecated... The new API brings ease-of-use and accuracy long provided by the popular Joda time API into the core Java library.

As with any new API the good news is that it’s more elegant and functional. Unfortunately there are still vast amounts of code out there using the old API, and that won’t change any time soon.

To help bridge the gap between the old and new API’s, the venerable Date class now has a new method called toInstant() which converts the Date into the new representation. This can be especially effective in those cases where you're working on an API that expects the classic form, but would like to enjoy everything the new API has to offer.



5. Controlling OS Processes

Launching an OS process from within your code is right there with JNI calls – it’s something you do half-knowing there’s a good chance you’re going to get some unexpected results and some really bad exceptions down the line.

Even so, it’s a necessary evil. But processes have another nasty angle to them - they have a tendency to dangle. The problem with launching process from within Java code so far has been that is was hard to control a process once it was launched.

To help us with this Java 8 introduces three new methods in the Process class -

destroyForcibly - terminates a process with a much higher degree of success than before.
isAlive tells if a process launched by your code is still alive.
A new overload for waitFor() lets you specify the amount of time you want to wait for the process to finish. This returns whether the process exited successfully or timed-out in which case you might terminate it.

Two good use-cases for these new methods are -

If the process did not finish in time, terminate and move forward:
if (process.wait(MY_TIMEOUT, TimeUnit.MILLISECONDS)){
       //success! }
else {
    process.destroyForcibly();
}
Make sure that before your code is done, you're not leaving any processes behind. Dangling processes can slowly but surely deplete your OS.
for (Process p : processes) {
       if (p.isAlive()) {
             p.destroyForcibly();
       }
}

6. Exact Numeric Operations

Numeric overflows can cause some of the nastiest bugs due to their implicit nature. This is especially true in systems where int values (such as counters) grow over time. In those cases things that work well in staging, and even during long periods in production, can start breaking in the weirdest of ways, when operations begin to overflow and produce completely unexpected values.

To help with this Java 8 has added several new “exact” methods to the Math class geared towards protecting sensitive code from implicit overflows, by throwing an unchecked ArithmeticException when the value of an operation overflows its precision.

int safeC = Math.multiplyExact(bigA, bigB); // will throw ArithmeticException if result exceeds +-2^31
The only downside is that it’s up to you to find those places in your code where overflows can happen. Not an automagical solution by any stretch, but I guess it’s better than nothing.

7. Secure Random Generation

Java has been under fire for several years for having security holes. Justified or not, a lot of workhas been done to fortify the JVM and frameworks from possible attacks. Random numbers with a low-level of entropy make systems that use random number generators to create encryption keys or hash sensitive information more susceptible to hacking.

So far selection of the Random Number Generation algorithms has been left to the developer. The problem is that where implementations depend on specific hardware / OS / JVM, the desired algorithm may not be available. In such cases applications have a tendency to default to weaker generators, which can put them at greater risk of attack.

Java 8 has added a new method called SecureRandom.getInstanceStrong() whose aim is to have the JVM choose a secure provider for you. If you’re writing code without complete control of the OS / hardware / JVM on which it would run (which is very common when deploying to the cloud or PaaS), my suggestion is to give this approach some serious consideration.

8. Optional References

NulPointers are like stubbing your toes - you’ve been doing it since you could stand up, and no matter how smart you are today - chances are you still do. To help with this age-old problem Java 8 is introducing a new template called Optional<T>.

Borrowing from Scala and Haskell, this template is meant to explicitly state when a reference passed to or returned by a function can be null. This is meant to reduce the guessing game of whether a reference can be null, through over-reliance on documentation which may be out-of-date, or reading code which may change over time.

Optional<User> tryFindUser(int userID) {
or -

void processUser(User user, Optional<Cart> shoppingCart) {
The Optional template has a set of functions that make sampling it more convenient, such as isPresent() to check if an non-null value is available, or ifPresent() to which you can pass a Lambda function that will be executed if isPresent is true. The downside is that much like with Java 8’s new date-time APIs, it will take time and work till this pattern takes hold and is absorbed into the libraries we use and design everyday.

New Lambda syntax for printing an optional value -

value.ifPresent(System.out::print);

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...