Archive

Posts Tagged ‘java’

Aparapi + Java + OpenCL


Since I’m working on OpenCL project, I was very curious to know, how to reduce the number of lines of code to be written for any program in OpenCL. While searching for the way to reduce the code I came to know the release of Aparapi.

It is an  API for expressing data parallel workloads in Java and a runtime component capable of converting the Java bytecode of compatible workloads into OpenCL so that it can be executed on a variety of GPU devices.

Some cool features of Aparapi are

* No need of thinking of explicit data transfers between host program and GPU kernel(If required you can do for the improvements purposes)

* No need of querying for the platform, devices

* No need of creating context and managing command queue

* No need of writing code for creating buffers

* No need of setting kernel arguments explicitly

* No need of using enqueNDRange()  and remembering so many parameters to set the globalThreads and localThreads and dimensions

* If GPU is not found still the Aparapi transforms the kernel code to use either JTP(Java Thread Pool) or CPU. Its not required to check explicitly if GPU is present or not and no need of explicitly creating threads to manage data parallelism.

* No need to learn C99 OpenCL C to write Highly data parallel applications

* Fast learning curve

*Aparapi is an open source project

Limitations of Aparapi

How ever Aparapi is having a lot of advantages there are some limiataions

* Cannot support local memory(Huge optimization loss here)

* May not reach the highly optimized openCL C wrapper performance for complex mathematical operations

Notwithstanding, no support for local memory Aparapi is great to use because most of the data parallel applications written in Java can hugely benefit from usage Java based Aparapi.

Aparapi Download link

Aparapi Getting Started

Installation Notes

Note: All the views presented here are just subjective and my personal perceptions. If there any thing wrong or I’m not updated with the future releases please notify me.

Thanks for reading!!

RMI in Java


In this post I’m going to write how I did RMI using java. This RMI program finds the current time of the server (on which the remote method is executed).

While implementing RMI in java we have to follow several steps.

step1: Create an interface which specifies what service server is going to provide or implement

/**
 *
 * @author Vasanth Raja Chittampally
 */

import java.rmi.*;
public interface TimeatServer extends Remote{
 public String showTime() throws RemoteException;
}

The above TimeatServer is an interface which is extending java.rmi.Remote contains the showTime() function which has to be defined in the server class. java.rmi.Remote specifies the the showTime() as the remote method which can be called from any virtual machine. All the methods which are declared inside the remote interface(An interface which has extended the java.rmi.Remote interface) are available Remotely.

step 2: Now we have to code the server implementation of above written TimeServer interface.

import java.rmi.*;
import java.rmi.server.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
 *
 * @author Vasanth Raja Chittampally
 */
public class TimeServerImpl extends UnicastRemoteObject implements TimeatServer{
    public TimeServerImpl() throws Exception {

    }

    public String showTime() throws RemoteException {
        Calendar calendar = new GregorianCalendar();
    String am_pm;
    int hour = calendar.get(Calendar.HOUR);
    int minute = calendar.get(Calendar.MINUTE);
    int second = calendar.get(Calendar.SECOND);
    if(calendar.get(Calendar.AM_PM) == 0)
      am_pm = "AM";
    else
      am_pm = "PM";
    return "Current Time : " + hour + ":"
+ minute + ":" + second + " " + am_pm;
    }
}

The above TimeSeverImpl.java extends the java.rmi.UnicastRemoteObject and implements the TimeServer interface. All the remote objects must extend UnicastRemoteObject because it provides the functionality through which the object becomes available from the remote machines.

step 3: In this step we have to bind the server implementation of the service with the service name

import java.rmi.*;
import java.rmi.server.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author Vasanth Raja Chittampally
 */
public class BindServer {
    public static void main(String[] args) {
        try {
            TimeServerImpl tsi= new TimeServerImpl();
            Naming.bind("time", tsi);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

In the above file we are binding the AddServerImpl object with the service name of “time”.
java.rmi.Naming.bind() function binds the service name with the service object.

step 4: Create client


import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Vasanth Raja Chittampally
*/
public class Client {
    public static void main(String[] args) throws NotBoundException {
        try {
            String url="rmi://127.0.0.1/time";
            TimeatServer ts=(TimeatServer) Naming.lookup(url);
             System.out.println(""+ts.showTime());
        } catch (MalformedURLException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RemoteException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

Client(Client.java) has to specify the url where exactly the server is available that is specified as a string using rmi://IP_ADDRESS/SERVICE_NAME. In the above example it was rmi://127.0.0.1/time.

127.0.0.1 specifies the localhost and time is the service with which we have bound the service in the BindServer.java file.

java.rmi.Naming.lookup() actually looks up for the service with the string specified in it, if it finds a service with the specified string then it returns its object. Using the returned object we are calling remote method showTime().
step 5: compile all the files till now we have create using standard javac command.

step 6: Generate the stubs

We actually need to have client stub and server stub. We first have to create stubs.

Here we can create only one stub.

In order to create the stub we have to compile using the RMI complier.

type

rmic -v1.1 TimeServerImpl

in the command prompt

then it creates two files TimeServerImpl_Stub.class and TimeServerImpl_Skel.class.

step 7:

now copy Client.class, TimeServer.class and TimeServerImpl_Stub.class into the client side machine.

copy all files except for the Client.class into the server machine.

Note: You can ignore the step 7 for the first time.

step 8: Now we have start the rmiregistry. Now let us go a little into the theory part. First server program binds the services to the binding registry. Client internally client stub checks for the service, if finds one, sends the marshalled parameters to the server stub. Now server stub unmarshalls the packaged parameters and calls the function then the returned results are marshalled or packaged by the server stub and sent to the client stub. now client stub unmarshalls the returned results and the remaining program will be executed at the client side.

inorder to register the services we have a tool called rmiregistry which is available from Java 2 SDK. open the terminal or command prompt and type

start rmiregistry

now you can see a separate window.

step 9: Run the BindServer.java program

using

java BindServer

step 10: Run the Client.java program

java Client

Output:

Current Time : 4:28:33 PM

Program to find practical numbers


In number theory, a practical number or panarithmic number is a positive integer n such that all smaller positive integers can be represented as sums of distinct divisors of n. For example, 12 is a practical number because all the numbers from 1 to 11 can be expressed as sums of its divisors 1, 2, 3, 4, and 6: as well as these divisors themselves, we have 5=3+2, 7=6+1, 8=6+2, 9=6+3, 10=6+3+1, and 11=6+3+2.

The sequence of practical numbers

1, 2, 4, 6, 8, 12, 16, 18, 20, 24, 28, 30, 32, 36, 40, 42, 48, 54, ….

Here is the Java code to find practical numbers in between given sequence.

/**
*
* @author Vasanth Raja Chittampally
*/
public class PracticalNumbers {
public int[] getPracticalNumbers(int from, int to) {
int a[]=new int[to-from];
int indx=0;
out:for (int i = from; i<=to;i++) {
int sum=0;
for(int j=1;j<=i/2;j++) {
if(i%j==0) {
if(sum<j-1)
continue out;
sum+=j;
}
}
if(sum>=i-1) {
a[indx++]=i;
}
}
int count=0;
for (int i = 0; i < a.length; i++) {
if(a[i]!=0)
count++;
}
int ans[]=new int[count];
for (int i = 0; i <count; i++) {
ans[i]=a[i];
}
return ans;

}

//  You could use this sample code to test function
//  Following main fucntion contains 3 representative test cases
public static void main(String[] arg) {
PracticalNumbers pn = new PracticalNumbers();
//1st test case
int[] res = pn.getPracticalNumbers(1, 20);
for (int i = 0; i < res.length; i++)
System.out.print(res[i] + " ");
System.out.println();
//2nd test case
int[] res2 = pn.getPracticalNumbers(8000, 8200);
for (int i = 0; i < res2.length; i++)
System.out.print(res2[i] + " ");
System.out.println();

//3rd test case
int[] res3 = pn.getPracticalNumbers(1000, 1120);
for (int i = 0; i < res3.length; i++)
System.out.print(res3[i] + " ");
System.out.println();
}
}

Here is the online ide where you can see the output

I feel the above program is self explanatory. If you have any doubts at any line please leave a comment. I’ll clarify your doubts. Thank you. I always welcome your comments or suggestions.

ArrayList and Iterator example


Here I want to share with you, the ArrayList and Iterator example. ArrayList is present in util package( java.util.ArrayList) means that we have to import before using it in our program. (import java.util.ArrayList) same as the case with Iterator too (import java.util.Iterator).

ArrayList and Iterator come very handy when we are dealing with a very big projects. Instead using static arrays we can easily, dynamically, create an array as a list and add reference of the elements to that. ArrayList can only take reference of the objects( I mean that we cannot give double, float or int as a reference instead we can use Wrapper classes such as Integer Double etc.,)

ArrayList class provides methods for basic array operations:

  • add( Object o ) – puts reference to object into ArrayList
  • get( int index ) – retrieves object reference from ArrayList index position
  • size() – returns ArrayList size
  • remove( int index ) – removes the element at the specified position in this list. Shifts any subsequent elements to the left and returns the element that was removed from the list.
  • indexOf( Object o) – finds the index in this list of the first occurrence of the specified element
  • clear() – removes all of the elements

Example program:

import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 * @author Vasanth Raja Chittampally
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        ArrayList al = new ArrayList(20); //Exactly equal to ArrayList  al = new ArrayList(20)
        for (int i = 0; i < 20; i++) {
            al.add(""+i);
        }
        Iterator i=al.iterator();

        while(i.hasNext()) {
            System.out.println(""+i.next());
        }
        System.out.println("In the second iteration");
        Iterator i1=al.iterator();
        System.out.println(""+i1);
         while(i1.hasNext()) {
            System.out.println(i1.next());
        }

    }

}

If we don’t provide any size in ArrayList al = new ArrayList(); it takes 10 as ArrayList size. Here in the above program Iterator takes the ArrayList and iterates from starting to ending in a forward direction. Ouput: it prints 0 to 19 two times. ArrayLists cannot work with the multiple threads.. Click here to read my previous post talking about the synchronization of ArrayList

Java Program to construct the Magic Square


Do you know what is Magic Square. Read here. Probably you might have played with this.

It is typically a matrix or table in which the sum of the elements of any row is equal to that of sum of the elements of any column and diagonal.

Here is the example of such magic square with dimension three

 

There are different ways to solve this. Here I took one of the easiest ways of solving it. Place the given user specified  input in the middle of the first row from that onwards keep on increasing the user given input by one and find the correct place for inserting that number. One way is find the upper diagonal element to that and place there if you find there is an already existing element then go down to the correct number and place there. If you go out of the square like in 3*3 table if 13 element go down i.e., 23 and place the element there. If you go out of the square beyond the column number then go to the first element like rotating method.

 

Program:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author Vasanth Raja Chittampally
 */
public class MagicBox {

    public static void main(String[] args) throws IOException {
        System.out.println("Enter the dimension of the matrix (Odd dimension only): ");
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int n=Integer.parseInt(br.readLine());
        if(n%2!=0) {
        int box[][]=new int[n][n];
        System.out.println("Enter the first element:");
        int firstEle=Integer.parseInt(br.readLine());
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                box[i][j]=0;
            }
        }
        int row=0;
        int col=n/2;
        for (int p = 0; p < n*n; p++) {
                box[row][col]=firstEle;
                firstEle++;
                row--;
                col++;
                if(row==-1)
                   row=n-1;
                if(col==n)
                   col=0;
                if(row==n-1 && col==0)
                {
                    row=1;
                    col=n-1;
                }
              if((box[row][col]!=0)) {
                   row+=2;
                   col--;
                 if(row&gt;n) row=0;
                if(col==-1) col=0;
            }
        }
        System.out.println("Magic Box");
         for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if(box[i][j]/10==0)
                    System.out.print( box[i][j]+"    ");
                else
                    System.out.print( box[i][j]+"   ");
            }
             System.out.println("");
        }
    }
}
}

Sample Input:
7
1
Output:
Magic Box
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20

Here is the same code if you want to try out use this online java compiler.

Adjacency list represention of graph in Java


Here is the program for adjacency list representation of graphs using java. If you are new to Graphs please read about graphs here before reading the rest of this post.

I used a List data structure inside the graph. I think much explanation is not required because it is very simple.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author Vasanth Raja Chittampally
 */
class List{
    int node;
    List next;
}

class Node {
    int node;
    List adjList;
}

public class Graphs {
    void insertVertices() throws IOException
    {
         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter number of nodes in a graph: ");
        int n=(Integer.parseInt(br.readLine()));
        Node g[]=new Node[n];
        for (int i = 0; i < n; i++) {
            g[i]=new Node();
            g[i].node=i+1;
            g[i].visit=false;
            while(true)
            {
                System.out.println("Enter zero to stop");
                System.out.println("Enter adjacent nodes to node "+(i+1)+" :");
                 int adjVertex=Integer.parseInt((br.readLine()));
                 if(adjVertex==0)
                     break;
                 else
                 {
                        List l=new List();
                        l.node=adjVertex;
                        l.next=null;
                        if(g[i].adjList==null)
                        {
                            g[i].adjList=l;
                        }
                        else
                        {
                            List p=g[i].adjList;
                            while(p.next!=null){
                                p=p.next;
                            }
                            p.next=l;
                        }
                 }
            }
        }
        System.out.println("Adjacency matrix representation");
        for (int i = 0; i < n; i++) {
            System.out.print(g[i].node+" --> ");
            List l=g[i].adjList;
            while(l!=null)
            {
                System.out.print(l.node+" --> ");
                l=l.next;
            }
            System.out.println("");
        }
    }

    public static void main(String[] args) throws IOException {
             new Graphs().insertVertices();
    }

}

Different types of data types


There actually different types of datatypes as the programming languages specify them. Here I’m going to specify four types of them, Almost all predominant languages should have datatypes belonging to the following four kinds of datatypes

1) Statically typed language

2) Dynamically typed language

3) Strongly typed language

4) Weakly typed language

Statically typed language:

In this kind of languages variables should be assigned types at the compile time itself( and fixed at compile time).  All the variables must be used before using them.

ex: Java, C, C++ ect.,

Dynamically typed language

It is exactly opposite to that of statically typed language. The type of the variable is decided at the runtime rather than at compile time.

ex:VBscript, Python

Strongly typed language

These kind of typed language don’t allow you to change the type of a variable once the type is decided(at runtime or at compile time). Once a variable is declared as String in Java during runtime you cannot convert the type of the variable without explicit type conversion.

ex: Python, Java

Weakly typed language

This type of languages are exactly opposite to that of Strongly typed languages, you can change the type of the variable at anytime during the execution of the program.

ex: VBScript