Friday, February 28, 2025

Building a GraalVM Native Image for Linux on Windows Using Docker


For Windows users seeking to create a GraalVM native image for a Linux environment, traditional approaches such as switching to Linux, dual booting, or using virtual machines can be cumbersome and inefficient. In this guide, we present a streamlined method leveraging Docker, enabling seamless development while retaining your Windows environment.

Traditional Methods and Their Challenges

Before exploring our Docker-based solution, let's review common methods and their limitations:

  1. Switching to Linux – This approach requires fully migrating to a Linux OS, causing loss of access to Windows-based applications.
  2. Dual Booting – Involves partitioning disk space for both Windows and Linux, requiring a reboot each time you switch between operating systems.
  3. Using a Virtual Machine (VM) – While providing a Linux environment within Windows, this method demands significant system resources and additional configuration.

A Modern Solution: Leveraging Docker

Using Docker, you can set up an isolated Linux environment within Windows, facilitating native image generation without the need for OS switching.

Step 1: Creating an Ubuntu-Based Docker Container

To establish an Ubuntu container with Git pre-installed, use the following Dockerfile:

# Use the official Ubuntu image as the base FROM ubuntu:latest # Set non-interactive mode to avoid interactive prompts ENV DEBIAN_FRONTEND=noninteractive # Update package lists and install Git and Wget, then clean up RUN apt-get update && apt-get install -y \ git \ wget \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* # Set the default command CMD ["/bin/bash"]

Step 2: Running the Container and Setting Up GraalVM

  1. Build and run the Docker container:
    docker build -t ubuntu-graalvm . docker run -it ubuntu-graalvm
  2. Clone your project repository inside the container using Git.
  3. Download and extract GraalVM manually:
    wget https://download.oracle.com/graalvm/23/latest/graalvm-jdk-23_linux-x64_bin.tar.gz tar -xvzf graalvm-jdk-23_linux-x64_bin.tar.gz
  4. Configure JAVA_HOME to point to the extracted GraalVM directory.
  5. Build the native image. For a Maven Spring Boot project, use:
    ./mvnw -Pnative native:compile

Step 3: Transferring the Native Image to the Local Machine

Once the native image is successfully built, copy it from the container to your Windows system using:

docker cp <container_id>:/app/project/webfluxtest/target/webfluxtest C:\Users\YourUsername\Documents

Step 4: Packaging the Native Image in a Linux-Based Container

To deploy the native image within a Linux environment, use the following Dockerfile:

# Use a minimal Ubuntu base image FROM ubuntu:latest # Install necessary dependencies RUN apt-get update && apt-get install -y libc6 && rm -rf /var/lib/apt/lists/* # Set working directory WORKDIR /app # Copy the prebuilt native binary into the container COPY webfluxtest /app/webfluxtest EXPOSE 8080 # Set execution permissions RUN chmod +x /app/webfluxtest # Define the entrypoint ENTRYPOINT ["/app/webfluxtest"]

Step 5: Building and Running the Final Container

  1. Build the Docker image:
    docker build -t webfluxtest-native .
    
  2. Run the container:
    docker run -p 8080:8080 webfluxtest-native
    

At this stage, your GraalVM native image is successfully running within a Linux-based Docker container, all while maintaining your Windows development environment.

Conclusion

By utilizing Docker, Windows users can efficiently build and deploy Linux-native GraalVM applications without the need for complex system reconfigurations. This approach enhances flexibility, optimizes workflow, and eliminates unnecessary overhead. Start leveraging Docker today for seamless native image development!


Saturday, November 18, 2017

java.SQl.Sqlexception:Invalid state, the connection object is closed

This exception seems to be wired to you are in suspected mode.Whenever you see this Exception below things comes in your mind
  1. Somebody written bullshit code, Executing query after closing connection object

    what if this is not the case, Then
  2.  If you are using any ORM framework, then might be ORM doing something
    or
  3. if you are using SQL driver, then might driver doing something
Apart from this, there is one more hidden cause which will act secretly on this, if you not aware of that i.e DB Configuration
let's take MSSQl DB for exploring thing

In MSSQL server under TCP connection configuration, there is a property is configured called KEEP ALIVE whose default value is set to 30000 milliseconds.
Let go in depth of KEEP ALIVE behavior, what it does.How database reacts to the time configured under KEEP ALIVE.DB expire the idle connection object if it exceeds the time limit configured under kEEP ALIVE.

How this impact on our application.
In Every application whenever we interact with DB, we will create the connection pool with some minimum count.Let's get in-depth how connection pool will get impacted with KEEP ALIVE property of DB
Let's assume DB connection pool is created with min count 5 and max count 10.While creating connection pool there is one property which is mandatory to know the value of that i.e IdleTime ( name can vary w.r.t driver, ORM ), which say up to what time connection can be idle.Now if IdleTime is more that KEEP ALIVE value and connection Object in the pool is idle more than KEEP ALIVE but less then IdleTime, then the connection object in a pool is getting expired from DB server side and when this connection object is used before IdleTime, you will face  java.SQl.Sqlexception: Invalid state, the connection object is closed.

So be aware while configuring connection pool. All DB connection pool is supposed to configure w.r.t DB configuration and your application activity like :

  • IdleTime should be always lesser than KEEPALIVE
  • If your application is not much-having heavy traffic then min connection should be in small count like 2 or 3
  • Max connection count depends upon how DB accept the connection.

Friday, January 23, 2015

Use Polymorphism and code to Interface instead of if and elseif

if elseif else comes under procedural programming, When we talk about Object Oriented programming we need to escape out from if elseif else  until any primitive data type is using for.Means In Object Oriented programming if elseif else is used only for primitive data type not for objects.


Let talk about some simple example with if else and try to convert this if else to purely object oriented.

suppose you have two user say "GUEST" and "ADMIN", w.r.t to this userType  you have to write  some bussiness logic.Since i am java developer and i need to think about Object oriented programming not  procedural programming .

Firt's let go with  most familiar flow which basically maximum java developer follow to do task and what's that

String userType=""//it can be either Guest or Admin

if("guest".equalsIgnoreCase(userType)){
doGuestBussinessLogic();
}
else if("admin".equalsIgnoreCase(userType)){

doAdminBussinessLogic();
}else{

throwExceptionOrDoNothing();
}


In don't know  about other but i definitely say that we are writing C-program in java Syntax

Now Lets try this in Pure java language

public interface User {
    public void bussinessLogicofUser();
}

public class AdminUser implements User {

    @Override
    public void bussinessLogicofUser() {
        System.out.println("Admin user bussiness logic started");
       
    }

}

public class GuestUser implements User {

    public void bussinessLogicofUser(){
        System.out.println("Guest user bussiness logic started");
    }
   
}

public enum UserType {
ADMIN(new AdminUser()),GUEST(new GuestUser());
User user;

private UserType(User user) {
  this.user = user;
}

public User
getUserTypeInstance(){
  return this.user;
}
}


Now in Main method where we write if else,it's time to delete that if else and write object oriented program.Let see how
try{
UserType.valueOf(userType.toUpperCase()).getUserTypeInstance().bussinessLogicofUser();
}catch(IllegalArgumentException e){
throwExceptionOrDoNothing();
}
Early we have written approx 7 line of code and here only 1 line code did that work.
That's the using of Object Oriented Program

Tuesday, January 8, 2013

How to configure Apache solr in Java

When we talk about search engine application then solr came in many of us mind.
In many tutorial we find that to use Apache solr we need to configure it inside server like tomcat but what if your tomcat get corrupted
at that time your solr project come in critical suitation.

Today i explain my personal experience of configuring about solr in project itself.

Fist step you need to download latest version of solr click here

NOw extract the download file and move to the following path "apache-solr-latest-version/example/".
there you find "solr" folder copy that folder and paste it in home directory.

Now again move to following folder "apache-solr-latest-version/example/webapps"
extract the solr.war and then move solr/WEB-INF/lib
now copy all jar file this jar file you need to add in your project lib folder

Now create Tomcat project/Dynamice web project as normally you do.

open web.xml file and add the following code


    <env-entry>
       <env-entry-name>solr/home</env-entry-name>
       <env-entry-value>${user.home}/solr</env-entry-value>
       <env-entry-type>java.lang.String</env-entry-type>
    </env-entry>

here we setting the path of solrconfig.xml files which is now inside ur home directory/solr/config we need to specify the path upto solr folder

  <filter>
    <filter-name>SolrRequestFilter</filter-name>
    <filter-class>org.apache.solr.servlet.SolrDispatchFilter</filter-class>
  </filter>

this is the main class which is use to initiate the solr configuration


Your confrigutaion is completed :)

now user home folder/solr/conf you get solrconfig.xml,schema.xml arranged it as per your requirement and start the server

If you really enjoyed this
give feedback
thanks...... :)
 

Wednesday, September 5, 2012

where Protocol of serialization is defined in java..??

Many of you used Serializable interface but have you ever think where the protocol of saving Serialization object is defned?
Today i share my knowledge about it how much i know

first lest go through the process of saving object.
class saveObject implements Serializable
{
public static void main(String args[])
    {
    saveObject sb=new saveObject();
    FileOutputStream fo=new FileOutputStream(fileName);
    ObjectOutputStream obs=new ObjectOutputStream(fo);
    obs.writeObject(sb);
    }
}
now if saveObject class implements Serializable then only it work else it throw exception saveObject is not Serialized
this protocol is define in inside ObjectOutputStream.writeObject(Object) method
lets check the method what it have
public final void writeObject(Object obj) throws IOException {
    if (enableOverride) {
        writeObjectOverride(obj);
        return;
    }
    try {
        writeObject0(obj, false);
    } catch (IOException ex) {
        if (depth == 0) {
        writeFatalException(ex);
        }
        throw ex;
    }
    }
here enableOverride is boolean type whose value get assign false inside ObjectOutputStream(fo) constructor
so  writeObject0(obj, false); get execute
now lets see what in  writeObject0(obj, false) method

    private void writeObject0(Object obj, boolean unshared)
    throws IOException
    {
    boolean oldMode = bout.setBlockDataMode(false);
    depth++;
    try {
        // handle previously written and non-replaceable objects
        int h;
        if ((obj = subs.lookup(obj)) == null) {
        writeNull();
        return;
        } else if (!unshared && (h = handles.lookup(obj)) != -1) {
        writeHandle(h);
        return;
        } else if (obj instanceof Class) {
        writeClass((Class) obj, unshared);
        return;
        } else if (obj instanceof ObjectStreamClass) {
        writeClassDesc((ObjectStreamClass) obj, unshared);
        return;
        }
       
        // check for replacement object
        Object orig = obj;
        Class cl = obj.getClass();
        ObjectStreamClass desc;
        for (;;) {
        // REMIND: skip this check for strings/arrays?
        Class repCl;
        desc = ObjectStreamClass.lookup(cl, true);
        if (!desc.hasWriteReplaceMethod() ||
            (obj = desc.invokeWriteReplace(obj)) == null ||
            (repCl = obj.getClass()) == cl)
        {
            break;
        }
        cl = repCl;
        }
        if (enableReplace) {
        Object rep = replaceObject(obj);
        if (rep != obj && rep != null) {
            cl = rep.getClass();
            desc = ObjectStreamClass.lookup(cl, true);
        }
        obj = rep;
        }

        // if object replaced, run through original checks a second time
        if (obj != orig) {
        subs.assign(orig, obj);
        if (obj == null) {
            writeNull();
            return;
        } else if (!unshared && (h = handles.lookup(obj)) != -1) {
            writeHandle(h);
            return;
        } else if (obj instanceof Class) {
            writeClass((Class) obj, unshared);
            return;
        } else if (obj instanceof ObjectStreamClass) {
            writeClassDesc((ObjectStreamClass) obj, unshared);
            return;
        }
        }
       
        // remaining cases
        if (obj instanceof String) {
        writeString((String) obj, unshared);
        } else if (cl.isArray()) {
        writeArray(obj, desc, unshared);
        } else if (obj instanceof Enum) {
        writeEnum((Enum) obj, desc, unshared);
        } else if (obj instanceof Serializable) {        //check this line
        writeOrdinaryObject(obj, desc, unshared);
        } else {
        throw new NotSerializableException(cl.getName());
        }
    } finally {
        depth--;
        bout.setBlockDataMode(oldMode);
    }
    }

as per different condition it perform the action i will not go in detail .Just go through the code where i comment check this line
here our condition get satisfied only if our class implements Serializable interface else it throw exception NotSerializableException
if obj not belong to Enum,String ,Class,ObjectStreamClass.
writeOrdinaryObject(obj, desc, unshared); do the rest thing of saving object
 
For reading object near about  same concept happened in
ObjectInputStream obi=new ObjectInputStream(new FileOutputStream(fileName));
obi.readObject()

Thursday, August 16, 2012

Cause of Error and Exception occur at Runtime in Java

1)java.lang.UnsupportedClassVersionError
This exception occur when you compile the java class with higher version of java environment and try to run that class file in lower version of java environment
for example if you compile the java class with java6 and try to  run that class with java5 you faced this type of exception

2)java.lang.NoClassDefFoundError
This exception occurs when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time.
possibility of this:
a) Class is not available in Java Classpath.
b) You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
c) Any start-up script is overriding Classpath environment variable.
d) Because NoClassDefFoundError is a sub class of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
e) Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to failure of static initialization is quite common.
f) If you are working in J2EE environment than visibility of Class among multiple Classloaders can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.

3)java.lang.ClassNotFoundException
This exception is nor similair with java.lang.NoClassDefFoundError because ClassNotFoundException comes when JVM tries to load a class at runtime dynamically means you give the name of class at runtime and then JVM tries to load it and if that class is not found in classpath it throws
java.lang.ClassNotFoundException. While in case of NoClassDefFoundError the problematic class was present during Compile time and that's why program was successfully compile but not available during runtime by any reason.

4)java.lang.ClassCastException
This exception occur when we attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:
         Object x = new Integer(0);
         System.out.println((String)x);

5)java.lang.ArrayIndexOutOfBoundsException
This exception occur when we accessed the array with an illegal index. The index is either negative or greater than or equal to the size of the array.
we always have to remember that The array indexes in Java start from 0 and go to array.length - 1

6)java.lang.NullPointerException
This exception is most common and every developer faced this exception once in there life.This exception occur when you performed any operation for null object.
To avoid this kind of exception check the null condition before performing any operation of object
for example
String s=null;//here s  is null at present and now if we preform
s.toString();//here you faced NullPointerException

always check null like
if(s!=null)
{
s.toString();
}
 

If you really enjoyed this
give feedback
thanks...... :)
    

Thursday, June 7, 2012

Jvm not only read Bytecode created by compiler and run it,apart from it, it do a lot work for us

while running this program i get stuck.
class A{
    static{
        System.out.println("A");
    }
    public static void main(String ar[]){
        System.out.println("A's main ");
    }
}
class B extends A{
    static{
        System.out.println("B");
    }
}
public class C {
    static{
        System.out.println("C");
    }
    public static void main(String[] args) {
        B.main(null);

    }

}

Now lest run the class C and see what the o/p is:
C
A
A's main 

As per java concept whenever class loaded in memory its static block get executed.its fine.....
now just move step by step for above program.
first class C is loaded in memory so class C static block execute first, then main() method get executed
now let see what inside main method of class C?
B.main(null)
ok

now what class B have?
have one static block only inside and extending class A..ok
now what class A have?
have a main method and one static block.here everything is fine
through class B we reaching to class A's main method because class B extending class A fine....
but when i check the output i have seen class B static block is not get executed means class B is not loaded to memory but without loading class B how class A get loaded..????
i discuss with many people, some say compiler do some edition when we compile the class.but what compler do..???
compiler never have a right to delete our single character then how class B get erased/override and if B is not erase/override then why class B is not loaded on the line executing"B.main(null)"
so by saying that compiler take care of this is absolutely wrong because compiler ony make our word meaningfull like for String it make java.lang.String and perform some complusray task if we not did like extending Object class and creating default constructor if we not create
Then i study JVM ,to know what actual JVM do
and  finally get the answer for this issue

Class are made available to a running program by the Java Virtual Machine. This is done through a process of loading, linking, and initialization. Loading is the process of locating the binary representation of a type and bringing it into the JVM. Linking is the process of taking the type and incorporating it into the runtime state of the JVM so that it can be executed. Initialization is the process of executing the initializers of a type (static initializers for classes; static field initializers for classes and interfaces). When a type becomes unreachable (i.e. the running application has no references to the type), it becomes eligible for garbage collection. This collection is called type unloading.

Here are the step follow when we run our any java program:
   1. Given a class's fully qualified name, produce a stream of binary data that represents that type
   2. Parse the stream of binary data produced in step #1 into internal structures in the method area of the JVM. The method area is a logical area of memory in the VM that is used to store information about loaded types.
   3. Create an instance of class java.lang.Class that represents the class indicated in step #1

According to this lets explain tha above details
B.main(null) come under binary data as mention in step #1
while parsing the data JVM link main(null) directly to class A becuase Main method exist in class A and load only class A
because of that class B not get overloaded


If you really enjoyed this
give feedback
thanks...... :)

Monday, March 19, 2012

Is downcasting is possible regarding object in Java

By the begining of Languages downcasting has a issue.lets checks with C-language
void main()
{
long i=98765431;
byte j=(byte) i;
printf(j);
}
here data overflow and get unexcepted result.
Before discussing this topic first we go through the defination of Upcasting and downcasting


What is upcasting?UpCasting is defined as casting a reference of a parent class type to a type of a reference to a child class.
What is downcasting?Downcasting is defined as casting a reference of a child class type to a type of a reference to a parent class.


Upcasting can de done automatically means implicity in java and
Downcasting we have to do explicity else we get compile time error


now lets going through the defination of upcasting and downcasting code the java program and check....


class parent
{}
class child extend parent
{
public static void main(String args[])

{
line 1: parent p=new child(); //upcasting happened complile and run successfully
line 2: child c=new parent(); // downcasting but not explicity so we get compile time error
line 3: child c1=(child) new parent(); // downcasting explicity compile success but give run time error class cast exception
}
}


now just read the downcasting defination above and check line 3 of above program,we are doing downcasting but it not happening here.


many of us say downcasting is happened in java and gave the example mention below


class parent
{}
class child
{

public static void main(String args[])

{
line 1: parent p=new child(); //upcasting
line 2: child c=(child) p; //downcasting,compile and run success
}
}


look carefully at line 2 we really doin downcasting,i don't think downcasting is not suitable word here we are doing here typecasting

in simple we can say that:
at line 1 we create object of child and say that you are parent type
and at line 2 we again saying to same child object that you are child type here where is the parent object that we are casting to child type..????

what is my opion on this issue is there i posted on this blog....
still have little bit confusion and hoping someone to clear this confusion

If you really enjoyed this
give feedback
thanks...... :)

Saturday, December 24, 2011

Secret in java

First look at the code:
Integer i=new Integer(5);
integer j=10;
here what happening two object is created of integer type whose value type is int
Integer value lies between -2147483648 to 2147483647
ok fine...

Integer i=127;
Integer j=127;
here what happen one object is created pointed by two referece i and j
lets see..
if(i==j)
{System.out.println("yes");}
else

{System.out.println("no");}

here o/p we get yes

Now once again.......

Integer a=128;
Integer b=128;
here what happen two object is created one pointed by  referece a and another pointing by reference b
lets see..
if(a==b)
{System.out.println("yes");}
else{System.out.println("no");}

here o/p we get no


How it happen...?????

Initially I too get shocked , how it happen?,i opened the book, surf the site then i came to the conclusion....

Bydefault jvm have limited heap memory which we can increase manually......
because of this bydefault limited heap memory Integers between -127 and 127 are 'cached' in such a way
that when you use those numbers you always refer to the same number in memory, which is why your == works.
In simple we can say that Integer value can be consider as three type

Data Type            Value                            Memory
byte            -128 -- +127                    occupy 1 byte (8 bits) in memory
short            -32768 -- 32767             occupy 2 bytes (16 bits) in memory
int            -2147483648 -- 2147483647   occupy 4 bytes (32 bits) in memory


and for least data type i.e byte value is cached in such a way that when you use those numbers you always refer to the same number in memory,because of limit heap memory
 


If you really enjoyed this
give feedback
thanks...... :) 

Tuesday, December 6, 2011

Check at what techniques your OS is working through Java.

There are two major types of scheduling techniques in the modern operating systems: round-robin and time-slicing.Now how can you identify at what techniques your OS is working through Java.

class Thready {
public static void main( String args [] ) {
new MyThread("A").start();
new MyThread("B").start();
}
}

class MyThread extends Thread {
String message;

MyThread ( String message ) {
this.message = message;
}

public void run() {
while ( true )
System.out.print( message );
}
}
if you get O/P:
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBB

then your OS is using Round Robin,The output is generated by an implementation of Java virtual machine for a preemptive system like UNIX OSF1, Windows 95, Windows NT, etc,

if your O/P is:
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA...........

then it using time-slicing ,the output is generated by an implementation of Java virtual machine for a non-preemptive system based on Solaris UNIX platforms


If you really enjoyed this
give feedback
thanks...... :)