Sunday, December 10, 2017

Multithreading in Java

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU
Multitasking can be achieved by two ways:
  • Process-based Multitasking(Multiprocessing)
  • Thread-based Multitasking(Multithreading)
Process-based Multitasking (Multiprocessing)

Thread-based Multitasking (Multithreading)

Each process have its own address in memory
Threads share the same address space
heavyweight
lightweight
Cost of communication between the process is high
Cost of communication between the thread is low

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.


Process is an executing instance of an application. For example, when you double click MS Word icon in your computer, you start a process that will run this MS word application.



  
Creating a thread,
1)      By extending java.lang.Thread class.

public class ThreadExtended {
public static void main(String[] arg){
//Creating a thread and starting it 
MyThread mt1 = new MyThread();
mt1.start();
}
}

class MyThread extends Thread{
public void run(){
// task for the thread
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}




2) By implementing java.lang.Runnable interface.

public class RunnableImplementation  {

public static void main(String[] arg){
//Creating a thread and starting it 
//MyThreadRI mt = new MyThreadRI();  // Creating an instance of  MyThreadRI
//Thread thread = new Thread(mt);  // Creating a thread using Runnable implemented object
//thread.start();
// Create a thread using Java 8
Thread t1 = new Thread(()->{
// task for the thread
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
});
t1.start();
}
}

class MyThreadRI implements Runnable{
@Override
public void run() {
// task for the thread
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}

Thursday, December 7, 2017

String in Java


String is an object that represents a sequence of characters. There are two ways of creating String,
1. by using String literal
2. by using new keyword
Strings created using “String Literal” are stored in “String Object Pool”. String Object Pool located in heap.
String Created using “new” keyword, stored String object in Heap memory (non pool) and create a literal in “String Object Pool”.




String is a final class in Java.

String is Immutable in Java hence can be safely used in multi threaded environment.
String Literals are used to get more memory efficient Because It don’t want create any object and if literal is already there it reuses it.

Why String objects are immutable in java?
Because String uses the concept of String literal. If String is mutable, When 5 variables refers to same String then Changing a variable value will affect to all the variables.

Thursday, January 16, 2014

Stored Procedure

Stored Procedure

Stored procedure is a block of code in database catalog and can be invoke later by a program.It just write the procedure in MySql then execute it.The procedure will save in catalog form that function name.You can see the procedure when you creating a backup file of  database schema in backup contain in Objecttype PROCEDURE. There are some advantages and disadvantages also.
Advantages
  •                 Reusable and transparent to any application. Stored procedures are not in our programming file but there in database.An application of any programming language can invoke that procedure  by invoking the stored procedure name.
  •                 It reduce the traffic between database server and application.
  •                 It is secured.Data base Administrator can grant access level by using stored procedure.

Disadvantages
  •                 It need a higher speed and higher capacity   database server.


Example:
DELIMITER //                                                         >>change the standard (;)delimiter to //
CREATE  PROCEDURE getAllUserDetaills()        >> name of the stored procedures
BEGIN                                                                   >> begin the actual query
SELECT * FROM USER                                       >>write the query
END//                                                                     >> end of the procedure
DELIMITER;                                                          >>change the delimiter to standard
 Can invoke the that procedure by using  CALL getAllUserDetails();.


Sunday, April 7, 2013

Singleton Design Pattern Using Java Example


The idea of the Singleton design pattern is that it ensures there is only one instance for a particular class and provide a global point of access to it by encapsulating just in time initialization or initialization on first use.

So there should be restriction for instantiation.

Now I’m going to explain how to implement the Singleton design pattern using Java example. Wait a minute. There are should be only one instance and a global access point in the program. Keep in mind always you work with the Singleton design pattern.

public class MySingleton{
    private static MySingleton singletonInstance;

    private MySingleton(){
    }

    public static MySingleton getSigletonInstance(){
        if(singletonInstance == null)
            singletonInstance = new MySingleton();
        return singletonInstance;
    }
}

Using private constructor, outside classes can not instantiate the class. So if we want to create an object, it should be within the class. By getSigletonInstance(), it provide a global access point to outsiders. It makes sure that there is only one instance by checking is there an instance, only there isn’t, it makes an instance. If there is an instance it returns the previous instance.  


What about we are working in a multithreading environment? If we use above program as it is, there may be instantiated some objects. So we have to prevent making more instance by make getSigletonInstance() method synchronize using synchronize key word.

public class MySingleton{
    private static MySingleton singletonInstance;

    private MySingleton(){
    }

    public static synchronized MySingleton getSigletonInstance(){
        if(singletonInstance == null)
            singletonInstance = new MySingleton();
        return singletonInstance;
    }
}

Now program is ok for multithreading environment. wait !!! What about performance? You should always think about the performance of the program. When you make the getSigletonInstance() method synchronize, all threads that want to access the method are in a queue and wait for acquire lock. So it is more time consuming and performance really go down.


There are some solutions for that. Did you think about an instance is created at class loading time? If not here it is.
public class MySingleton{
       private static final MySingleton singletonInstance = new MySingleton();
    private MySingleton(){
    }

    public static MySingleton getSigletonInstance(){
       return singletonInstance;
    }
}

By final instance, it ensures that  singletonInstance instance   can not be redefined. So there is only one instance. By making that instance static that instance is created at the class loading time. So when MySingleton is deployed, at that time singletonInstance instance is created.There is no synchronized method so it performs well.

Another way to do this is Enum and it is the best way. The use of an enum is very easy to implement and has no drawbacks regarding serializable objects because it is thread safe. Java program guarantee that it has only one instance. Since there is global access point it protects the singleton.

public enum MySingleton {
    INSTANCE;
    public void execute (String arg) {
            //... perform operation here ...
    }
}

Practically Singleton pattern is used in Database connector class. Mainly Singleton pattern use in resource saving activities.

According to your requirement you are free to select a way to implement the Singleton.

Your comments give encourage to grow up. Best of luck!!

Introductions to REST


Rest architecture style is stateless client server protocol and always it uses HTTP .Rest stands for Representational  State Transfer. In Restful application Rest use HTTP for all curd operations (Create, Read , Update, Delete). So Rest is very lightweight  by comparing other RPC(Remote Producer  Calls) and web services.

Rest API has some advantage like platform independent ,language independent ,run top of HTTP,able to use in the presence of firewalls easily. But there is no inbuilt security features in Rest. But  security features can be added like username/password tokens.

Rest operations  are self contained and each and every request carry all the information to the server  that it need to complete the request. So there is no cookies in good Rest design.

Rest request :-
http://www.mytutorialparadise.com/useraccount/111  -It’ll retrieve the user details of 111th  user.

http://www.mytutorialparadise.com/useraccount?name=Kamal$nic=12234342  It’ll retrieve the details of person which named Kamal and have nic of 12234342.

The server response in Rest is often an XML file but CSV(Commar seperater value) and JSON (JavaScript Object Notations) formats can use.XML is easy to expand and type safe.CSV is more compact and JSON is  easy to parse.

Thursday, February 21, 2013

Hibernate tutorial


Hibernate is a powerful high-performance Object/Relational persistence and query service for Java applications. In Hibernate it maps object oriented classes to the database tables and also provides data query. It’s so simple and easy.

Before come to Hibernate, I’ll get some time to explain where it is come from.

There are some mismatches, when mapping object oriented classes and relational databases. Here we want to use a technique to map them correctly. So Object Relational Mapping here. Object Relational Mapping is used for avoid following mismatches between   object oriented classes and relational data bases.

There may be more classes than the number of corresponding tables in the data base. Relational data bases do not defined any similarity to inheritance which is main concept in OOP. RDBMS only has concept of sameness while OOP has object identity and object equality. RDBMS is used foreign key for association columns while OOP is used object reference. The method of access to object class and RDBMS is different.

For more clear, I’ll give you a example for class and data base table.
public class Student {
   private int id;
   private String name;
   private int telno;
   

   public Student() {}
   public Student(String name,int telno) {
      this.name = name;
      this.telno = telno;
   }
   public int getId() {
      return id;
   }
   public String getName() {
      return name;
   }
  
   public int getTelno() {
      return telno;
   }
}

Above program is Java student class and By creating a object we are going to store data in following table.

create table STUDENT (
   id INT NOT NULL auto_increment,
   name VARCHAR(30) default NULL,
   telno INT  default NULL,
   PRIMARY KEY (id)
);

There are some advantages over traditional JDBC (Java Data Base connectivity). There are no need to deal with data base implementation. It hides details of SQL queries from OO logic. Entities are based on business concepts rather than database structure. It is developed application faster.

There are many Java ORM Frameworks. Here we use Hibernate framework which provide services to store and retrieve objects from relational data base.

Hibernate exist between java objects and database server to handle object –relational mechanisms and patterns by mapping java classes to database tables and from java data types to SQL data types.








Hibernate supports RDBMS like MySQL, Oracle, HSQL Database Engine, DB2/NT, PostgreSQL, FrontBase, Microsoft SQL Server Database, Sybase SQL Server , Informix Dynamic Server and technologies like J2EE, Eclipse plug-ins, XDoclet Springand, Maven.



The Hypervisor

 The hypervisor is a piece of software that runs on top of hardware infrastructure that creates a virtualization platform. The hypervisor a...