Showing posts with label Tutorials. Show all posts
Showing posts with label Tutorials. Show all posts

Friday, September 10, 2021

What is Java Virtual Machine (JVM) & Its Architecture

What is JVM?

JVM is a engine that provides runtime environment to drive the Java Code or applications. It converts Java bytecode into machines language. JVM is a part of JRE(Java Run Environment). It stands for Java Virtual Machine

  • In other programming languages, the compiler produces machine code for a particular system. However, Java compiler produces code for a Virtual Machine known as Java Virtual Machine.
  • First, Java code is complied into bytecode. This bytecode gets interpreted on different machines
  • Between host system and Java source, Bytecode is an intermediary language.
  • JVM is responsible for allocating memory space.

In this tutorial, you will learn-

  • What is JVM?
  • JVM Architecture
  • Software Code Compilation & Execution process
  • C code Compilation and Execution process
  • Java code Compilation and Execution process
  • Why is Java both interpreted and Compiled Language?
  • Why is Java slow?

JVM Architecture

Let’s understand the Architecture of JVM. It contains classloader, memory area, execution engine etc.



1) ClassLoader

The class loader is a subsystem used for loading class files. It performs three major functions viz. Loading, Linking, and Initialization.

2) Method Area

JVM Method Area stores class structures like metadata, the constant runtime pool, and the code for methods.

3) Heap

All the Objects, their related instance variables, and arrays are stored in the heap. This memory is common and shared across multiple threads.

4) JVM language Stacks

Java language Stacks store local variables, and it’s partial results. Each thread has its own JVM stack, created simultaneously as the thread is created. A new frame is created whenever a method is invoked, and it is deleted when method invocation process is complete.

5) PC Registers

PC register store the address of the Java virtual machine instruction which is currently executing. In Java, each thread has its separate PC register.

6) Native Method Stacks

Native method stacks hold the instruction of native code depends on the native library. It is written in another language instead of Java.

7) Execution Engine

It is a type of software used to test hardware, software, or complete systems. The test execution engine never carries any information about the tested product.

8) Native Method interface

The Native Method Interface is a programming framework. It allows Java code which is running in a JVM to call by libraries and native applications.

9) Native Method Libraries

Native Libraries is a collection of the Native Libraries(C, C++) which are needed by the Execution Engine.

Software Code Compilation & Execution process

In order to write and execute a software program, you need the following

1) Editor – To type your program into, a notepad could be used for this

2) Compiler – To convert your high language program into native machine code

3) Linker – To combine different program files reference in your main program together.

4) Loader – To load the files from your secondary storage device like Hard Disk, Flash Drive, CD into RAM for execution. The loading is automatically done when you execute your code.

5) Execution – Actual execution of the code which is handled by your OS & processor.

With this background, refer the following video & learn the working and architecture of the Java Virtual Machine.

C code Compilation and Execution process

To understand the Java compiling process in Java. Let’s first take a quick look to compiling and linking process in C.

Suppose in the main, you have called two function f1 and f2. The main function is stored in file a1.c.


Function f1 is stored in a file a2.c


Function f2 is stored in a file a3.c


All these files, i.e., a1.c, a2.c, and a3.c, is fed to the compiler. Whose output is the corresponding object files which are the machine code.


The next step is integrating all these object files into a single .exe file with the help of linker. The linker will club all these files together and produces the .exe file.


During program run, a loader program will load a.exe into the RAM for the execution.




Java code Compilation and Execution in Java VM

Let’s look at the process for JAVA. In your main, you have two methods f1 and f2.

  • The main method is stored in file a1.java
  • f1 is stored in a file as a2.java
  • f2 is stored in a file as a3.java

The compiler will compile the three files and produces 3 corresponding .class file which consists of BYTE code. Unlike C, no linking is done .

The Java VM or Java Virtual Machine resides on the RAM. During execution, using the class loader the class files are brought on the RAM. The BYTE code is verified for any security breaches.


Next, the execution engine will convert the Bytecode into Native machine code. This is just in time compiling. It is one of the main reason why Java is comparatively slow.


NOTE: JIT or Just-in-time compiler is the part of the Java Virtual Machine (JVM). It interprets part of the Byte Code that has similar functionality at the same time.

Why is Java both Interpreted and Compiled Language?

Programming languages are classified as

  • Higher Level Language Ex. C++, Java
  • Middle-Level Languages Ex. C
  • Low-Level Language Ex Assembly
  • finally the lowest level as the Machine Language.

compiler is a program which converts a program from one level of language to another. Example conversion of C++ program into machine code.

The java compiler converts high-level java code into bytecode (which is also a type of machine code).

An interpreter is a program which converts a program at one level to another programming language at the same level. Example conversion of Java program into C++

In Java, the Just In Time Code generator converts the bytecode into the native machine code which are at the same programming levels.

Hence, Java is both compiled as well as interpreted language.

Why is Java slow?

The two main reasons behind the slowness of Java are

  1. Dynamic Linking: Unlike C, linking is done at run-time, every time the program is run in Java.
  2. Run-time Interpreter: The conversion of byte code into native machine code is done at run-time in Java which furthers slows down the speed

However, the latest version of Java has addressed the performance bottlenecks to a great extent.

Summary :

  • JVM or Java Virtual Machine is the engine that drives the Java Code. It converts Java bytecode into machines language.
  • In JVM, Java code is compiled to bytecode. This bytecode gets interpreted on different machines
  • JIT or Just-in-time compiler is the part of the Java Virtual Machine (JVM). It is used to speed up the execution time
  • In comparison to other compiler machines, Java may be slow in execution.

Thanks for Reading 
Noeik





Saturday, March 9, 2019

Real time Logs of AWS Elastic Beanstalk by Command Prompt

Many of us know that one of the most important services of AWS is Elastic beanstalks. We deployed our application on Beanstalk and AWS itself manage most of the thing in it. One of them is Logs of Applications.


People usually were not able to see the tail of the logs of the application what they need to do is to go to the beanstalk and under logs, they ask for the last 100 lines of logs or full logs (which include the of the application along with the other logs ).



Today we will learn how to connect with the beanstalk application through EB CLI and see the logs.


let's follow the below steps.
  1. Install the Python Once installed run below commands
  2. python --version
  3. pip --version
  4. pip install awsebcli --upgrade --user
  5. once ebcli installed successfully, you can check by 
  6. eb --version
  7. define the Python Home in your Environment Variable.
  8. Now Run your command prompt as Administrator  and write 
eb init --interactive
You will see the below image.
  • Now select the region you have deployed your application.
  • After that, you will be asked to Create a new Application 
  • Once your application will be created you will see below screen.
  • You need to select the appropriate platform you have used for your application.
  • Now Once you do it you will be asked to create the SSH 
Select Yes 
  • Then they will ask you to create the keypair 


  • Provide your password  and then you will see the below image 
  • Now you have successfully created your SSH and it is uploaded to your beanstalk as well.
  • you need to attach the SSH with the Application.

Follow below steps 

eb ssh <Application-name> --settings

  • You will get the list of options then it will ask for the keypair which you need to attach.
  • Select the appropraite one.
  • After selecting the one you will be asked to enter the password set earlier.
  • You will then have the Applicaiton connected.
  • Once connected successfully you will be getting below image.
Now go to 
/var/log/tomcat8 ( to see the application logs, if your application is deployed on tomcat)

I Hope you will be able to connect your local machine to EB , If you have any issue  ,Please leave us a comment we will look into it.

Also Read:
  1. Spring Boot and Hibernate Tutorials - Application using Spring Boot
  2. What is Spring boot ?
  3. How to read value from property file in spring boot ?
  4. First Rest API Application - Top Spring Framework Interview Questions
  5. Implementation of Swagger in Spring boot
  6. How to use h2 database in spring boot

Thanks for reading.



Saturday, February 16, 2019

Database Timezone issue -Solution in java

We have at least once in our development has encountered one issue with database and client location is Timezone difference. 



In most of the cases, Our Backend /Application server is in a different timezone and our client server is in a different timezone. So what actually the problem happens is the difference in data time because of Timezone.

Wednesday, November 28, 2018

Thread Pooling In Java Using Executors Class

Most of the Important and most of the developer found one topic in java they perform a task and then they get destroyed. Purpose of multithreading is to perform multiple tasks simultaneously for effective utilization of our resources (time and CPU).


Imagine that there are 10 tasks to perform, so using traditional multithreading mechanism we will need 10 threads. Do you see a drawback in this approach? I see it; creation of a new thread per task will cause resource overhead.

Sunday, September 2, 2018

Remote Debugging of Java Application deployed on AWS Elastic Beanstalk

Most of the time we stuck in the situation where we need to do remote debugging of the application which is running on some server or somewhere other than localhost. We need to debug the code in eclipse. To do that we need to allow the running application to allow remote debugging. 


Generally, we know how to do remote debug in eclipse while the code is running on tomcat. In this post, we will see how to do remote debug when the application is deployed over AWS by elastic beanstalk.



Let's start.

To do Remote debug of AWS deployed the application, we need to follow below steps.

1)We need to Go to AWS Console -> Elastic Beanstalk -> Application -> Configuration

2) Under Configuration you need to go to Software ->Modify ->Container Options 
 Now in Container Options, search for JVM options    In this text box you need to write the below arguments.
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005
Now, these arguments say that - The remote debug will be listening at 5005 port.

3) Now you need to Go to EC2 Instance running from AWS Console -> EC2

4) After that you need to check which security group is defined for that EC2 Instance, you need to allow this port to communicate outside AWS.

5)For that, you need to add the Port in Inbound and Outbound of the Security Group
   Select the Custom Protocol and define the Port as 5005 and then define Anywhere in Ip accessible.

After this, you will be able to communicate the port with the local debugger of the eclipse.

Now you need to configure the Local Eclipse environment for Remote debugging.


Configure Local Eclipse 


For this you need to go to  Run ->Debug Configuration -> Remote debugging 

Under that define the IP of the application ( you need to find the IP of the application at EC2 Instance Properties )

Define the port as 5005 ( as defined above).

Run the application and hurray, are now connected with the AWS application running.

Now you will be able to debug remotely.

Hope you like the post, If so please share it with your friends and family.

Thanks for reading
Noeik

Saturday, August 18, 2018

Upload File on AWS S3 Using Java

Most of us know nowadays that AWS  is used for almost everything because of its cheap price as well its availability.

AWS S3 is an online storage for storing file and images and zip, literally everything you want to put. 

Most of us have some use cases where we want to upload the image to aws s3 so that it can we used anywhere we want.

#Usercase we need to get the file or Image from UI and need to upload it to AWS S3 using java.

#Approach To Achieve it 
  • first, need to add the AWS SDK for Java 
  • Then we need to Get the client of AWS which is basically creating a connection with AWS 
  • After successfully getting the connection we will use s3 API to put the image as an object in AWS.

We first need to Add the dependency of AWS SDK in our project ( maven dependency as below )

  <dependency>
   <groupId>com.amazonaws</groupId>
   <artifactId>aws-java-sdk</artifactId>
   <version>1.11.388</version>
 </dependency>

After this, we need to have the AWS Account Access key and access_id
you can get it from https://console.aws.amazon.com/iam/home?#/security_credential

Access key file will look like below

[default]
aws_access_key_id=<Your-Access-key_id>
aws_secret_access_key=<Your Secret_access_key>
Note change <Your-Access-key_id> and <Your Secret_access_key> values with your access key.

Now you need to save the access key file at a location below.

~/.aws/credentials on Linux, macOS, or Unix
C:\Users\USERNAME \.aws\credentials on Windows

Now let see the Code for the Uploading of Image /File on AWS.  (Ref : here )
 we will create one jsp file where we create upload file and call the spring controller , under the controller, you can see the file and it will store to the aws s3.




Thyemleaf Html Code

<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
<title>File Upload Example</title>
<link href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"
 rel="stylesheet" />
<script type="text/javascript" src="webjars/jquery/3.3.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>
<script th:inline="javascript">
 /*<![CDATA[*/
 var _validFileExtensions = [ ".csv", ".zip" ,".png" ];
 function Validate(oForm) {
  var arrInputs = oForm.getElementsByTagName("input");
  for (var i = 0; i < arrInputs.length; i++) {
   var oInput = arrInputs[i];
   if (oInput.type == "file") {
    var sFileName = oInput.value;
    if (sFileName.length == 0) {

     alert("Please select a file to upload");
     return false;
    }
    if (sFileName.length > 0) {
     var blnValid = false;
     for (var j = 0; j < _validFileExtensions.length; j++) {
      var sCurExtension = _validFileExtensions[j];
      if (sFileName.substr(
        sFileName.length - sCurExtension.length,
        sCurExtension.length).toLowerCase() == sCurExtension
        .toLowerCase()) {
       blnValid = true;
       break;
      }
     }

     if (!blnValid) {
      alert("Invalid File Extension");
      return false;
     }
    }
   }
  }

  return true;
 }
  
 /*]]>*/
</script>

<body>

 <div class="container-fluid padding-0">
  <div class="row padding-0">
   
   <div class="col-md-4">
    <h2>File Upload Example</h2>
   </div>
   <div class="col-md-4" align="right"></div>
  </div>
 </div>
 <nav role="navigation" id="trainingset-container-id"
  class="navbar navbar-default">
  <div class="row" style="margin-top: 10px;">
   <div class="col-md-2">
    <B>Upload File</B>
   </div>
   <div class="col-md-6">
    <form method="POST" action="/upload"
     onsubmit="return Validate(this);" enctype="multipart/form-data">
     <div class="col-sm-6">

      <input type="file" name="file"  />
     </div>
     <div class="col-sm-6">
      <input type="submit" class="btn btn-success btn-sm" value="Upload data" />
     </div>
    </form>
   </div>
   
  </div>
 </nav>
  <div id="messageboxid">
   <div id="uploadstatus" th:if="${message}">
    <B>Status Of Uploaded File</B>
    <h6 th:text="${message}" />
   </div>
  </div>
  
</body>
</html>
This will see like this

Now we will see the Upload Controller Code.

Upload Controller.java

package com.programinjava.learn.controller;

import java.io.InputStream;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;

@Controller
public class UploadController {
 
 @PostMapping("/upload")
 public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {


  if (file.isEmpty()) {
   redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
   return "redirect:uploadStatus";
  }
//  bucket name 
  String bucketName ="atserve-photos";
//  get it from user or change it 
  String nameOffile ="myPhoto";
//  getting aws access 
  AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                .withRegion(Regions.AP_SOUTH_1)
                .withCredentials(new ProfileCredentialsProvider())
                .build();
  boolean isBucketExist =s3Client.doesBucketExist(bucketName);
  if(!isBucketExist) {
   s3Client.createBucket(bucketName);
  }
  try {
   InputStream is = file.getInputStream();
   s3Client.putObject(new PutObjectRequest(bucketName,nameOffile,is,new ObjectMetadata()).withCannedAcl(CannedAccessControlList.PublicRead));
   redirectAttributes.addFlashAttribute("message", "SuccessFully Uploaded On AWS S3");
  }catch(Exception e) {
   e.printStackTrace();
  }
  return "redirect:/uploadStatus";
 }
 
 @GetMapping("/uploadStatus")
 public String uploadStatus(ModelMap m) {
  return "Homepage";
 }
 
 @GetMapping("/upload")  
 public String displayHomePageForAlarm() {
  return "Homepage";
 }

}

Let see what we get on AWS S3

So this is how we can see the myPhoto is now uploaded on AWS S3.

DOWNOAD THE CODE :


Also, learn

Thursday, July 19, 2018

Comparator interface and its example in java


In our previous post we have learn about what is comparable , In this article we will see basics about Comparator.


#What is Comparator ?
Comparator is a interface which is used to order the different user defined objects. When we have 2 object of different classes we want to order them we will use comparator.

Learn about What is Comparable?

#UserCase :
We have an array of person , we want to sort them on different basis , like on the basis of age of the person , or on the basis of name of the person. there are 2 questions comes in our mind , can we use comparable , - No ( as we can only compare on one of the 2 basis not both) , can we use comparator - Yes .




Approach 

  1. We will first create one person class .
  2. Now we will create 2 different Custom Comparator classes which will implements Comparator<person>
    1. One will be AgeComparator.
    2. Second will be NameComparator.
  3. Now we will create one Main class where we will create list of person. and then we will use Collections.sort and pass the list along with the comparator , we want to use for sorting.
Implementation

Person.java

class Person{
 
 int age;
 String name;
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 @Override
 public String toString() {
  return "Person [age=" + age + ", name=" + name + "]";
 }
 
 
 
}
AgeComparator.java

class AgeComparator implements Comparator<Person>{

 @Override
 public int compare(Person arg0, Person arg1) {
  // TODO Auto-generated method stub
  return arg0.getAge() - arg1.getAge();
 }
 
}
NameComparator.java

class NameComparator implements Comparator<Person>{

 @Override
 public int compare(Person o1, Person o2) {
  // TODO Auto-generated method stub
  return o1.getName().compareTo(o2.getName());
 }
 
}

Main Class

public class ComparatorDemo {
 public static void main(String[] args) {
  List<Person> list = new ArrayList<>();
  Person p1 = new Person();
  p1.setAge(35);
  p1.setName("vishal");
  
  Person p2 = new Person();
  p2.setAge(45);
  p2.setName("rohan");
  
  
  list.add(p2);
  list.add(p1);
  
  
//  Collections.sort(list,new AgeComparator());
  Collections.sort(list,new NameComparator());
  list.forEach(s-> System.out.println(s));
 }
 
}

Result 

Person [age=45, name=rohan]
Person [age=35, name=vishal]

Here we can see that the Objects are sorted on the basis of name , we can also do it by using age comparator as well.

If you have any issue , Please let us know , if you want any other topic to be covered in our next article please leave us a comment.

If you like this article please share it with your friends as well.

Thanks for reading
noeik

Saturday, July 14, 2018

Comparable and its example in java

comparable interface and its example

Most of us have heard about comparable and most of you also know what is comparable,
What is a comparable interface?
Comparable interface is used to sort the objects on the basis of any one variable, It is found in java.lang package and contain only one method compareTo(Object o).

In java When we have a scenario where we need to sort the array of objects on the basis of there member variable, or to eligible the objects to compare we use Comparable.

There are some good interview questions are there related to the comparable interface.

In this article, we will see one example of the implementation of the comparable interface and its explanation.



#Objective - We have a list of student and we need to sort the list on the bases of student ages in ascending order.

#Approach
  • We will implement the Comparable interface in the student class.
  • we will override the compareTo() method and write the logic for that 
  • As compareTo() method return 
    • 1 when own variable is greater than compared object variable.
    • 0 when both are equal
    • -1 when the own variable is less than compared object variable.
Now let see the implementation.
Below is the Student class

package com.programinjava.learning.comparable;


//implementing the comparable interface
public class Student implements Comparable<Student>{
 
 
 private int age;
 private String name;
 
 
 

 public int getAge() {
  return age;
 }




 public void setAge(int age) {
  this.age = age;
 }




 public String getName() {
  return name;
 }




 public void setName(String name) {
  this.name = name;
 }

 @Override
 public int compareTo(Student o) {
  return this.getAge() - o.getAge();
 }




 @Override
 public String toString() {
  return "Student [age=" + age + ", name=" + name + "]";
 }
 
 

}
Now we will see the Main Demo class

ComparableDemo.java
package com.programinjava.learning.comparable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparableDemo {
 
 public static void main(String[] args) {
  
  
  
//  creating list of student with different name and age
  List<Student> list = new ArrayList<>();
  Student s1 = new Student();
  s1.setAge(10);
  s1.setName("student 1");
  
//  second
  Student s2 = new Student();
  s2.setAge(20);
  s2.setName("student 2");
//  third
  
  Student s3 = new Student();
  s3.setAge(30);
  s3.setName("student 3");
  
//  fourth
  Student s4 = new Student();
  s4.setAge(40);
  s4.setName("student 4");
  
//  fifth
  Student s5 = new Student();
  s5.setAge(50);
  s5.setName("student 5");
  
  list.add(s2);
  list.add(s1);
  list.add(s4);
  list.add(s3);
  list.add(s5);
  
  System.out.println("Printing before sorting the list");
  list.forEach(s->System.out.println(s));
  
//  sorting the list 
  Collections.sort(list);
  System.out.println();
  
  System.out.println("Printing after sorting the list");
  list.forEach(s->System.out.println(s));
  
  
 }

}
Result Looks like below
Printing before sorting the list
Student [age=20, name=student 2]
Student [age=10, name=student 1]
Student [age=40, name=student 4]
Student [age=30, name=student 3]
Student [age=50, name=student 5]

Printing after sorting the list
Student [age=10, name=student 1]
Student [age=20, name=student 2]
Student [age=30, name=student 3]
Student [age=40, name=student 4]
Student [age=50, name=student 5]

I hope this will help you in understand how to implement comparable and when to implement it.

There are some other topics if you want to explore


Conditional Logic in java
Loops in java
Arrays in java
Wrapper classes in java
Methods in java
Object Oriented Practices
Inheritance in java

If you have any issue, please leave us a comment, if you like it, please share it with your friends

Thanks for reading 
noeik