Issues with Java 7 on Mac OS

Posted on 18th April 2013 in Blog, Java, Technical

At my work place, I was involved in building a desktop application for Mac (priority) & Windows (lesser priority). So for about 5 months, I did all my development work on Mac and now I think I have a good feel of the OS.

So the application was built using  JavaFX. There were native calls to be made to some C libraries, and I used awesome JNA to do it. But in the whole, I had a terrible time working with JVM on Mac and below is a list of why it is such a pain:

 

Some History:

Till Snow Leopard (not sure), Java came per-installed on Mac. Apple had its own bindings to HotSpot VM. But after Java 7, Apple decided to stop porting JDK and Oracle provided the built. And here starts, half the problems:

(In no particular order)

  • Firstly it is excruciating working with Java 7 based desktop applications . Do not even try it on Retina display; For the font.  It is horrible and blurry. I use Monospaced 13 on eclipse and it is pathetic. And I dont think any more text can ever describe how blurry and pathetic it is.

It is a registered bug which will only get fixed by Java 8 (What!!). It seems the behavior is due to the fact that Oracle built does not support HiDPI. A quick working solution is to use Apple Java 6 to run your applications if you can . For eclipse and netbeans, here.

  • A lot of apple libraries such as Quick Time and others are 32-bit builds. The canon sdk, I was working with only has a 32-bit build available. And only a 32-bit JVM can do native calls with 32-bit libraries. Apple Java 6 is a 64-bit VM and can be run in 32-bit mode using `-d32` jvm argument.

The issue: Java 7 no longer supports `-d32` option. Which means you cannot use it to call 32-bit native libraries. And this breaks half the code. Hence, I simply cannot use Java 7 for development.

  • It is buggy. Our client was Norwegian. Obviously, he had a lot of files named in Norwegian. The issue: Java 7 could not detect files that were named with non-ascii characters (norwegian). (This was caught at the client side and believe me it hurts when you see this happen).  It was a bug which was solved but the damage was done.

And then it was corrected. But during testing, I realized that the DirectoryChooser of javaFX did detect them, and on user selection, weirdly returns null instead of file. I have submitted the bug. But again it was painful telling the client not to use files/directories with Norwegian characters. And I had no time building a custom component.

With all the above, it was still important to use Java 7. We wanted to build a cross-platform application and had no developer resources to write them separately for each OS. This made C/C++ out of picture. We did not want to use Adobe Flex (license & future maintenance issue). Not python, as no one in team knew it and we all were comfortable with Java.

We built on Java 7 because:

  • Apple does not give license to redistribute VM along with application. But my company people wanted to port it along. Hence Java 6 cannot be used.
  • We wanted to use JavaFX (awesome MVC UI toolkit) and not Swing. JavaFX looked promising (which actually is) and hence the decision was taken. But unlike windows, JavaFX build is only available from Java 7 on Mac. Hence we are stuck with it now.

The only positive was this small issue, which worked well on windows and not on Mac.

 

PS: There are a lot more and will keep adding up the list as time permits.

comments: 0 » tags: ,

Continuation….

Posted on 20th November 2012 in Blog, Java, Technical

This post is in continuation to the previous post – Co-variance and Contra-variance

 

Arrays in Java are Co-variant. Which basically means if “String” extends “Object” then “String[]” also extends “Object[]“.
Do you see  any pitfall’s above??

Lets look at the following example

Example - 1
String[] a = new String[]{"Hello","Hey"};
Object[] b = a;//line 2
b[0] = new Integer(23);//line 3
a[0] =???

Now because arrays in Java are co-variant, you can do the above. a[0] now will refer to an Integer which is illegal. To prevent this line3 will throw an ArrayStoreException at runtime. Truly this should actually be caught at compile time.
Thanks to co-variance of arrays for behavior. Because for some reason arrays were decided to be co-variant and they are reifiable, i.e. they retain the type information at runtime. Which allowed us to do line-2 but also gave us line-3. To prevent this, they manually had to check the type info for every access of array which again is bad and extra overhead.


But why were arrays made co-variant??

Java founders wanted to have Generics right from day 0 (Generics were introduced in Java 5). Generics follow type erasure, i.e. the type is checked for compatibility and erased at compile time. More on it here. Due to lack of time, they had to postpone it. Now without generics a method like this would had been impossible. Unless Arrays were made co-variant.

Arrays.sort(Object[] ob)

The above method takes an object array and sorts them based on the Comparables. Hence a single method will suffice. Without covariance of arrays, they will be a need to write a separate method for each of the Data Type. Hence the decision.

Another consequence is that you cannot instantiate an array of a generic type. Nothing special for generics.

Example - 2
List<String>[] l = new ArrayList<String>[10]();//line 1
Object[] a = l;
List<Integer> l2 = new ArrayList<Integer>();
a[0] = l2; 
l[0] = ??? //list of string or integer?

Hence line-1 is illegal. Though arrays with wild-cards are allowed i.e. List<?>. Why is left for user to analyse. Similarly, why Generics were decided to be invariant is again left to the user (Hint: Similar to the above example, try adding any animal (pig) to list of dogs)

So now we have seen that writing onto co-variant mutable types always throws one or some other trouble. This gives gives rise to 2 questions:

  1. If Arrays were invariant, would it solve the purpose?
  2. If Arrays were left co-variant, what change can be made to make it correct? Has mutability has got anything to do with it?

Suppose Arrays were invariant, then the bugs would be detected right at compile time as raised in Example -1. Thus Invariance of Arrays looks to be the right way forward. Scala gets this right.

Lets look at the second question. Suppose Generics below were co-variant. Lets consider immutable List for example. (By ImmutableList I mean, any addition to the list creates a new List by copying the previous elements and adding the latest element. Similar to CopyOnWriteArrayList just that addition returns a new List every time)

ImmutableList<String> a = new ImmutableList<String>();
ImmutableList<String> b = a.add("Hey");//line2
ImmutableList<Object> x = a;//line 3
ImmuabltList<Object> y = b.add(new Object);

In Line-2, adding a string returned immutable list containing only “Hey”. ImmutableList “a” still is empty. Now on adding Object in Line-4 gave a new List containing (“Hey” and an “Object”) to become “y”. The return type of list is “Object”. Hence it is safe at all the stages. As now “y” is a list of Objects containing a “Hey” and an “Object.

So it turns out that with immutability, co-variance can be used safely. Com’on Co-variance is such a lovely tool. It lets you do stuff like if A <:  B then it is handy to have C[A] <: C[B]. Isn’t it?

So remember [P2] (from last post). Preferably with rights co-variance can be trouble-some. Perfect for Reads just like returns in functions.

 

Interestingly Contra-variance is made for writes. More on it and beautiful implements of it in Scala in the next post.

 

comments: 0 » tags: , ,

Co-variance & Contra-variance

Posted on 19th November 2012 in Blog, Java, Technical

I have been working on Scala recently and it has been a pure pleasure. I am in love with the language. And Yes! it indeed is a beast.

Generics/Parametrization is something that has always kept me on the hook even after good amount of experience in it. Thanks to Scala and lectures by Martin Odersky, I am much better now. There have been some realizations on the go, but to explain that I will first have to explain some basics. Though theoretical and boring at many places, I promise this will improve your architect skills if understood well :)

I have planned the post in 4 parts:

  1. Brief overview of Co-variance & Contra-variance
  2. Above paradigm behavior in Java, Python, C#
  3. Overview and short-comings of Generics in Java. Design flaw with Arrays
  4. A detailed theoretical explanation with help of Scala

Before starting, there is one very important theorem called Liskov Substitution principle in object oriented world. This should always be behind your mind while designing API’s. It states-

Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.

The above means- If “A” extends “B” (A <: B), then all the things that one can do with “B” should also be legal with “A”.

 

Co-variance & Contra-variance

 Wiki will give you a formal definition. Crudely:

  • Co-variance ( <: ) is converting type from wider type to narrow. In Java terms- ? extends E*
  • Contra-variance (>: )is converting type from narrow to wider. In Java terms- ? super E*
  • In-variant cannot be converted
* Where E is generic type declared and “?” is a wild card which crudely means “Anytype”
So for example:
class Animal {
}
class Dog extends Animal{
}
class Example{
  void run(){
     Dog dog = new Dog();
     getAnimal(dog);
}
void getAnimal(Animal animal){
.....
}
}

In the above example, one is ultimately doing

Animal animal = dog

So you are converting a dog type (narrow) to Animal type (wider). This is contra-variance. The reverse of it is Co-variance. The above paradigm is also followed in C# and python.

For co-variance:

class A{
  Animal getCreature(){
    return new Dog();
  }
}
class B extends A{
  Dog getCreature(){
    return new Dog();
  }
}

Check the return type of the getCreature function. getCreature() ultimately returns an Animal. But it returns type of Dog in class B. This is co-variance. The above is perfectly legal, because the code that invokes getCreature() of class A expects an Animal in return; which class B provides a Dog (ultimately dog is an animal. Vice-versa wont work, think!)

Invariance is when the type cannot be converted.

By default return types of functions in Java, C# and python are co-variant and argument types are invariant.

Points to Remember:

I will raise some points now and the explanation will be given by the end. The whole point of the post are the below points.

  1. Contravariant types can only appear in places, where you write something (i.e. parameter types) and covariant types can only appear in places, where you read something. [P1]
  2. Co-variance is only suitable when the data is immutable. More on it below. [P2]

I will first raise the issues caused in Java by not following [P1] i.e Arrays disaster for which Generics (type erasure) will be discussed. And then issues with [P2]. Finally improvements and how the issue was dealt successfully in Scala in the next post :)



													
comments: 0 »

Cache

Posted on 18th August 2012 in Blog, Java, Technical

This is  the first part of series of posts I plan to put-up on effective memory-centric cache implementations.

Well I have been working and going through different cache implementations in Java. Below is a discussion on some of them. The aim is to choose the perfect cache for a respective scenario. Below I have tried to explain the basics of Java dependencies to keep it language independent.

 

Now in general it is found out that LRU (Least Recently Used) is preferable for most of the scenarios. And it can be very easily be implemented in Java by extending a beautiful data structure “LinkedHashMap” and overriding removeEldestEntry(final Map.Entry<A, B> eldest).  More on it here. But the issue with it is the size. How will you set the size of the cache? If the cache size is too small, it would not solve the purpose. If it is too large, it might eat away applications required memory.

Fixing the size of the cache indeed is tough. Ideally you would want a cache that scales according to the application. Under low memory consumption by application, one wont mind cache taking too much of memory. Under high memory contention, one would want cache size to decrease (though it will create performance problems as cache might be non-existent then. But it is atleast better than repetitive Full GC’s).

 

Hence I have been in search for an effective implementation of Cache which is:

  • LRU
  • Size variant depending upon the available Memory.

Though it is still work in progress, I will be discussing about the second option above in this post and the next. And a culmination of both in the third post.

 

Scaling of Cache

The aim is be to generate specifications based on quantitative analysis to for a perfect outlook to implement such a scenario.

To implement such a case, we need some support from the language which shall timely give us input about the available memory; Better if it can itself remove objects from cache. Luckily Java gives us this flexibility be providing us with a java.lang.ref package which provides limited communication with Garbage Collector.

For analysis here I have taken the code from from org.neo4j.kernel.impl.cache package of Neo4J graph database. I have slightly modified the code to generate statistics. The code is a property of NeoTechnologies and is used here only for educational purposes. It very well implements what we desire. The link to cache is here. Primarily it has 2 cache versions:

  • SoftRefCache
  • WeakRefCache
Both of them internally use ConcurrentHashMap data structure which hold a key-value pair. The difference in both above is that- SoftRefCache uses a SoftReference wrapper above the value  and WeakRefCache uses a WeakReference wrapper above the value pair in the HashMap.
The key is that – under different memory scenarios, the objects in cache automatically become Softly or Weakly reachable and ultimately becoming ready for garbage collection. Hence cache scaling according to needs.

Cache & Performance – In Worst Case Scenario

 

I have carried some tests to decide which version should be used under what scenario. The below is analysis under high contention where all different objects are repeatedly added to cache. In reality, this can only happen under heavy stress.

The code to exhibit the above can be found out at CacheTest.java inside cache.neo4j package. Roughly it is:

private void go() {
SoftLruCache<EntityInteger> cache = new SoftLruCache<EntityInteger>(“Soft Cache”);
test(cache);
}

private void go2()
{
WeakLruCache<EntityInteger> cache2 = new WeakLruCache<>(“Weak Cache”);
test(cache2);
}

private void test(ReferenceCache<EntityInteger> cache) {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
cache.put(new EntityInteger(i));
}
}

Below is individual analysis for each of the case. Though it is not true comparison of cache’s but rather SoftReference and WeakReference.
My configuration:

java version “1.7.0_05″
Java(TM) SE Runtime Environment (build 1.7.0_05-b05)
Java HotSpot(TM) Client VM (build 23.1-b03, mixed mode, sharing)
Windows 7.
intel i3 processor.
JVM arguments: -server  -Xmx200M -verbose:gc -XX:+PrintGCDetails (Xmx means JVM can at max hold 200 mb of RAM)

 

SoftLruCache

Below is a graph of size of cache vs time.

 

The memory behavior:

* Above the memory result is not correct as profiler itself might be consuming decent amount of memory. Without loss of generality, once can assume that it is consuming about 80-100 mb.

And the log.

Results:

  • The memory expand to full 200mb allotted, after which results in repeated Full GC’s which frees up memory. During which, the cache size drastically reduces from ~1,700,000 to mere 400,000.
  • The above cycle is repeated periodically. With the cache size increasing to 1,400,000 and then a drastic fall to less than 100,000. In some cases to even below 1000.
  • On an average, around 75% of applications running time was spent in Garbage Collection.
Analysis:
You for sure will face your administrators wrath if you are going to use it in such a case. 75 % time on GC is just a straight kill. Basically cache fills up till there is no more memory available. Which yields in Full GC. A lot of memory is cleared up and the cache again starts filling up.
Actually people might not agree with me. Here the objects are added at a very very fast rate. So its no wonder that performance is so bad. Though yes waiting till there is no memory available to clear up might be a bad option (as it might effect applications functioning). But in cases where you know that the size of the cache might never grow such significantly high; And even if it does, if the objects are not added at such high rate later. It is actually might be a good option.
To verify the above, I modified the program as: As soon as more than 3,000,000 elements are added to cache, reduce the rate of addition to cache by 500 times. The results were:
  • Time spent on GC reduced to less than 50% and below.
  • Constant memory consumption of 160 MB. This is different from previous results.
  • Cache size hardly ever went below 1,000,000 which in a way is a good thing.

Next post will be the same analysis on Weak Reference. Later repetition for a more realistic scenario

References:

For more on java.lang.ref:

  1. http://docs.oracle.com/javase/7/docs/api/index.html

 

comments: 1 »

Another reason to love Neo4J

Posted on 22nd May 2012 in Blog, Java, Technical

For one of the projects where Neo4J is being used, I have been working on implementing K-Shortest Path algorithm using Yen’s loopless improvised algorithm.

Now an issue in the algorithm is that; Say  in computing top 4 shortest path, what the algorithm does is that it when computing the 2nd shortest path; It removes arcs of the 1st shortest path from the graph. And so removes the 2nd while computing 3rd shortest path and so on. And later in the end, it adds back all the removed arcs.

The problem now is that when one thread is computing a kth shortest path, other threads cannot use the algorithm as the graph is not in its complete shape. i.e. because first thread in the computation has temporarily removed some arcs, and the same graph cannot be used for any other purpose till those arcs are again added. Hence multiple instances of the algorithm cannot be used in parallel. One can solve the problem by  instead of removing them, have a flag in the relationship for a particular par of nodes. Flag will be cleared once the computation is over. But when running many instances in parallel there shall be many  such key value pairs in the relationships.There is an extra load in teh end to clear the flags.

Now this would have been a problem while using any other graph library. But the transaction model in Neo4J solves the above issue.

Here is the crazy part which I am unsure of if at all its a good practice:
I will have the code inside a transaction, but not let the transaction succeed. i.e. I will implement the algorithm and remove the respective arcs in the process, when I have the desired output, I will call the transaction a failure. hence the arcs are never removed and the same instance of the algorithm can be used. Further there will be no need to later add those arcs as in reality they were never removed.

This is so cool. Though there is another issue with it as pointed out by Mattias Persson of NeoTechnologies-

The only problem I  see here is that removing relationships will grab write locks which will be held throughout the transaction and prevent any other shortest path algo to remove those relationships as long as the transaction is alive.

How big this issue is, I do not know. But if carefully crafted should behave well. In any case its way better than removing the arcs and halting all the other computations on the graph.

More on it here.

 

New Development:
Another reason why I use N3o4J is to reduce the development time.  Reason being had I used some graph service at expense of memory, rebuilding the graph even to test small things takes a lot of time. With Neo4J I dont have to worry about that. Though with JUNG the problem can be solved by using a custom class loader and using the test’ as plugins hence saving time. But all this requires effort.

 

 

comments: 0 »

MIT IMI

Posted on 20th March 2012 in android, Blog, Projects, Technical

In the summer of 2011, I (in a team of five) had participated in Massachusetts Institute  of Technology, Indian Mobile Initiative – The NEXT BIG IDEA Challenge. We had constructed an App cum service called KickStart. The below are the certificates with official MIT hologram :)

 

 

 

 

PS: The article which appeared on KickStart in Navhind Times

 

 

comments: 0 »

WiiChat

Posted on 20th March 2012 in android, Blog, Projects, Technical

 

Wii-Chat is a peer to peer android chat service built by myself and Shubham Atlani under BITS Pilani Android Research group.
Using Wii-Chat one can communicate with another in a Wii-Fii. Currently by using the existing version one can only chat. Development is going on to extend the existing framework to include VoIP. This later will be merged with the internal VoIP phones enabling phone call from anywhere to anyone within the University premises. Hence direct call’s within the campus will be free. The only question is will the bandwidth be in a position to handle the data flow. But again like I said this is a research project and they are meant to be ambitious :P

The Chat version is built and hence the framework to merge phone call’s is complete. Stay in tune here for more information.

comments: 0 »

Inter Thread Task Transfer

Posted on 20th March 2012 in Blog, Java, Uncategorized

Most of my projects (infact all of them) are only 80% complete and have not published them anywhere. Hence finally thought that it is high time now to complete Unfinished Business :) . The next few posts will only be explaining th different libraries I had made for fun but later realized that they actually are useful :P

 

First in the sequence is a small library I had made probably 6-7 months ago; which I call it as Inter Thread Task Transfer. Their respective source codes are available at github under MIT license.

I first built it inspired from Looper & Handler in Android. But then later realized due to the wrong design pattern chosen to construct it, it is not scalable at all. Hence only provides basic features. Frustrated with design I choose a new Design Pattern (which till now is working fine :) )  and worked on it to construct the same thing. But the code can be extended to several other features and infact is pretty useful in general life.
In nutshell Every thread can create a handle which is to be merged with Looper. Using this handle another thread can send the respective Runnable’s and Callable’s to the owner thread. Also the API provides functionality to get the returned values. Hence threads can share their load among a group.

Small functionality which can be added is that currently threads can only provide but not take. That can be very easily extended.

PS: Some problem with the github account, you can download the previous code from here and with the better design here.

 

comments: 0 » tags:

Nirmaan – An Experience

Posted on 14th February 2012 in Blog, Life in General

Nirmaan – An Experience, My Experience…..

 

It so happened that till I was 16, my upbringing was at a place called Mubarak Nagar 5 KM’s away from Nizamabad which is 170 KM away from Hyderabad. Mubarak Nagar is a typical south Indian village which used to suffer from the usual problem what average villages in the country face. Currently there is not much problem due to modernization and quite good governance. But I had seen the evolution of Mubarak Nagar from a place where 60% community were involved in naxalism, where Law and order was horrible and pathetic, where Liquor and Spirits were destroying the hormonal existence of society, where there was very high illiteracy and poor medical facilities etc. Hence I had the complete view of what problems the whole community had undergone and always had a soft corner in heart to try help villages grow in every aspect I can.

And so when I came across Nirmaan after joining this campus, initially I was a bit resistant to join probably because I had not much idea about the work which Nirmaan was doing. But when finally came to know the complete details from Tarin Bansal, I immediately joined it in no time. Nirmaan was different, different because there was complete freedom of thought irrespective of which year you were in. Also everyone was giving their best to make sure all the tasks were completed in an effective manner. But the best part was that Nirmaan was working in root of the problems, instead of focusing on outer layers. It was tough because it involved a lot of field work, but that is what personally made me strong.

Apart from service, on a personal side it made me more confident, more determined and made me stronger to face tough situations. A lot of credits also have to go to the Ex-Com team for the sheer determination and strong commitment they had. For example I remember in November, when a student committee was formed by SWD, to aid some campus welfare initiatives, I remember Kunjan, Manoj(Sorry if I forgot anyone else) etc having discussions regarding what initiatives to take so that in future smart people from campus join Nirmaan instead of the other committee. Hats off to their Vision and commitment which I truly admire.

Overall a brilliant experience. Nirmaan volunteer for life.

Jatin Puri

comments: 0 » tags:

Clojure for Netbeans 7.*

Posted on 12th February 2012 in Blog, Java

For sometime now I have thinking to explore my domain and for a change learn a new Language. Inspired from the talk by Dr.Dragan Djuric on Clojure, I decided to go behind Clojure.

As a Netbeans enthusiast I was looking for a plugin for Clojure. On first Google search came across Enclojure which is a Netbeans plugin for Clojure. From the explanation, I followed the instructions to install it on my 7.0.1 version. But on installing it threw the following error:

Some plugins require plugin Lucene Integration to be installed.
The plugin Lucene Integration is requested in version >= 2.10.1.232
(release version 1) but only 3.2.1 (of release version different from
1) was found.  The following plugin is affected:       Enclojure
Clojure Plugin
Some plugins require plugin Editor Library to be installed.
The plugin Editor Library is requested in version >= 2.10.1.10.2
(release version 2) but only 3.9.1.13.10 (of release version different
from 2) was found.  The following plugin is affected:       Enclojure
Clojure Plugin

On searching realized that this is a common problem for installing it on > Netbeans 7.*. But with some manual tweeks managed to install it. Here are the instructions to install on Netbeans 7.* plus:

  1. Install Netbeans 7. You need only the Java SE version.
  2. First Run of Netbeans after installation. Activate feature Java SE
    • Activate features is on the Start page or from Tools,->Plugins>Installed, click ‘Activate next to the Java SE support
    • Install Maven
    • It is HIGHLY recommended that you install maven: http://maven.apache.org/download.html
    • Go to the Netbeans->Preferences, click on the Miscellaneous tab and make sure the External Maven Home path is pointed to your maven install
  3. Download the EnClojure 1.5 version from here. If you want  to manually build, you can do that by following the instructions from here.
  4. After downloading the file, In Netbeans: Goto:- Tools ->Plugins->Downloaded->Add Plugins->Downloaded (as shown in the figure below)
    Then browse to the downloaded file. Later install by clicking at the “install : button.
  5. Restart and you are on the go.
  6. Visit hereto build and run hello world project.Basically building the EnClojure 1.5 manually is the tough job. I hope above was useful.
comments: 3 » tags: ,

Approach for Effective Concurrency

Posted on 10th February 2012 in Blog, Java

Somehow in last 8 months I have been working on things which needed effective Thread-Safe libraries. So in due process of making them I had encountered different approaches in dealing with them in terms of the mutability of the data. This blog is related to the best approach I have realized:

Transaction

Well in a way almost all major frameworks follow it. The database model’s are built around it. But from a developer point of view I will tell you the reason why I prefer it the most:

  1. When a transaction is committed, the changes or the inputs in the transaction is the only stuff which needs to be done at that particular moment. Thus in a way there is no need to deal with the situation where you expect many changes from different threads all the time. The libraries are Thread-Safe through Thread Confinement. The Transactions can be executed wither sequentially or in parallel depending upon the scope of the transaction but ultimately satisfying Thread Confinement. Thus solving the whole problem of building design models rather than updating data/states on the go.
  2. One of my favorite quotes:
    Nature Loves Simplicity
    -Johannes Kepler

    The whole concept of a transaction is pretty simple for a developer who is working on an API built around it. it is simple to understand and execute.

  3.  Response: For example Neo4J: I just love the whole format of how data/traversals in nodes/relationship’s are embedded inside a Transaction. As an neo4j programmer it is pretty simple to me; That if the transaction is succesful then the changes shall be made or else not. In other cases where every change is to be made, making a response system would make it complicated in return.

This was one of the problems I faced while working on ISO standard 5 for GNU prolog for Java. In a way I should have followed the same transaction model given almost all follow it. Clojure also does it the same way (but only provides ACI instead of ACID)

 

comments: 0 » tags: ,

Sort in Lucene

Posted on 31st December 2011 in Blog

There are so many different posts I want to add, that in the thought of making them I am making none :P

Well have been recently working on Neo4J . Neo4J is a Graph Database. It has several advantages over Relational Databases where there are a lot of traversals ( For examples in Social Networking sites, where one moves from one friend to another frequently). With updating and traversal, each traversal requires a Join operation. And Join’s are known to be expensive. Further its tough representing common data structures like ordered lists, hierarchies, trees or web page content in Relational DB.

Well this post is not about Graph DB vs Relational Db. That will come sometime later.

Neo4J internally uses a text processing engine called Lucene (Yes! twitter heavily relies on Lucene). So just for fun, I had indexed 3 lakh nodes in Neo4J. And as I said Neo4J uses lucene, I gave a small query to sort these 3 lakh nodes depending upon their unique random number allotted to them.

And I also using HeapSort sorted 3 lakh random numbers. The below are the results:

So it took 1.593 seconds to sort 3 lakh random nodes. And 0.468 to search a node with some other random number.
Quick Sort takes 0.3 seconds. HeapSort takes 0.25 sec (MergeSort should be the best choice, but had to code and implement it, heapsort should be pretty close).
Well 1.593 sec is absolutely brilliant as there is i/o involved because it needs to load the nodes from the database. So with all that, its quite impressive.

PS: My comp config -
2.4 GHz, Quad Core
4 GB RAM
32-bit Windows 7
Java version:
“1.7.0_01″
Java(TM) SE Runtime Environment (build 1.7.0_01-b08)
Java HotSpot(TM) Client VM (build 21.1-b02, mixed mode, sharing)

comments: 2 »

Graph Library

Posted on 20th December 2011 in Blog, Java, Projects, Technical

Well I do know that there are some amazing Open Source Graph Libraries out there, but during the course of the last semester I happened to make one for myself.

It so happened that for quite some time now I have learning a lot about Object oriented Design Patterns (From the book Head First Design Patterns, its an amazing book and do read if you haven’t read Gang of four or this before. Highly highly recommended, already in my list of top 3 books for Java). And due to my unsatisfiable thirst for growth in Concurrency, I thought why not lets design a Graph Library which provides internal synchronization in the library. By internal synchronization I mean a mechanism where one could lock all the access to a node or an edge and do the required processing. JGraphT or Jung for that matter do not provide it.

Further we were suppose to make an ADT for graph’s for the course Data Structures and Algorithms, so I thought finally a perfect opportunity to club my interests with academics (Sadly never used it for academics). But ultimately with all the assignments and tests I couldn’t design it for concurrency, but yes the library does form a basic architecture on which I can build up later.

Salient Feature of GraphS (Yes! I named it GraphS which means Graph with Synchronization) :

  1. Traversal is through nodes rather than by retrieving from indexed list. Hence One can lock the operation on a Node. (More work needed with blocking and non-blocking features)
  2. Follows all the good Design Patterns and guaranteed for Scalability.
  3. Abstract Class Graphs.java  has the basic implementation of a graph. DirectedGraph.java & UnDirectedGraph.java extends it.
  4. API provides 2 shortest path Algorithm Implementations : Dijkshtra’s and Bellman Ford Algorithms
  5. API provides 2 MST Implementations : Krushkal and Prim’s
  6. Well Tested

There is a lot of work which needs to be done:

  1. Complete the synchronization part as explained above
  2. Improve the Documentation.
  3. Implement the GUI component.
  4. Profile it with more than a million nodes and compare it with other Graph libraries.

Somehow couldn’t use it for my course work but hopefully the experience of building it would be handy as for next I would be working on Neo4J which is a Graph Database.

People interested to build it firther, pl write to me at jatin@jatinpuri.com.You can download the source code from github under MIT license.

 

PS: Some problem with my github account, for now you can download it from here.

 

comments: 0 » tags: , ,

Guest Lecture at Spectra 1.0

Posted on 26th November 2011 in android, Blog

We (I and Nehil) were invited to give a Guest Lecture at Spectra 1.0, the technical Festival organized by Department of Computer Science, Shree Damodar College Margaon; In association with Department of IT, Government of Goa.

The lecture was primarily an Introduction to Android and about the technologies revolving around it. You can download my presentation from here

In short the outline of the presentation:

  • Android – A brief History
  • Android Internals
  • Why you should care about Android
  • Android App in 15 Minutes
  • The Future

I was roughly covering the first two and Nehil the rest with the third one as the intersection. The audience was surprisingly very enthusiastic.

                                                                     Audience

 

When I started my talk so as to increase the audience participation, I asked them a question to tell me anything they know or heard about Android. Some of the answers were impressive; From it was started by Andy Rubin to the use and need of Linux Kernel etc. Hence at that moment I knew that these people were sincerely interested in the talk and that pumped me more.

 

 

After about speaking for 45 Min, Nehil continued with a short introduction to App Inventor. We thought that App Inventor was necessary as it a very simple tool to build app’s quickly. His introduction was the best I have seen in recent past with he getting hold of the audience in hardly a minute. You can find his presentation here.
It was a nice experience for us. Thanks to the organizers of the fest especially Mr.Sumit and Mr. Mangesh sir from Bits for giving us this chance. Hopefully some more lectures around the corner :)

PS:
1) Nehil’s  post.
2) Pics from our Talk

comments: 3 » tags:

Happy Diwali

Posted on 27th October 2011 in Blog, Life in General

Happy Diwali!!

Bawa (Yes!+ architect) had written a beautiful post some years back on his blog on diwali. Its a brilliant article which I make sure to read it every year:

One the eve of Deepawali

from baus blog

Most people believe that business and spirituality are at loggerheads with each other. A person doing business cannot afford to be spiritual and a person who is spiritual shouldn’t care about business. This is what the so called experts say…

The Ancients knew better!!

The Goddess of Wealth Laxmi signifies the epitome of Business. She sits on a lotus which is in water. Meaning that wealth and prosperity can be very fleeting. Any moment they could sink! Also the lotus signifies a fully blossomed consciousness and that only such a person is really capable of handling wealth effectively. The finances of a country (or a family for that matter) need to be managed by extremely capable hands, other wise, the wealth (and the country) could go under very fast… (America… You listening to this?!  )

To drive home that Wealth is best in the hands of someone extremely skillful and with a fully blossomed consciousness, Laxmi is married to Lord Narayana… The epitome of Spirituality, the very First Guru. Narayana means one with a highly sensitive and fully developed nervous system. He is the Preserver aspect of the Holy Trinity. Also from His navel springs forth a Lotus in which sits Lord Brahma, the creator of all. So He also has the creative impulse at His command. Only such a person can handle and maintain wealth effectively!

Narayana is usually depicted lying on the Shesh Naga, the King of serpents who is floating on an ocean of milk. This is such beautiful symbolism! The King of serpents is His seat, meaning that He is supremely aware… yet He is lying down, relaxing, which signifies that though He is super aware and alert at all times, He does it effortlessly… The ocean of milk signifies extreme abundance… An infinite ocean of wealth is His!

To such a one comes Goddess Laxmi as wife.

Not only do business and spirituality complement each other… They are married to each other!

A hard core business person (with no spirituality) has the habit of monetizing everything. See a beautiful painting, think ahhh … Rs 5 Lakhs! See a lovely bungalow, think hmmm… Rs 25 Crores and so on… Even after acquiring all, he cannot appreciate what he has, coz all he can see around him are small and big piles of money. He has no ability to appreciate and enjoy the finer things in Life… Many Gujju friends come to mind

When such a person learns and practices meditation, his heart opens up… He realizes that there is life beyond money. He learns to enjoy his money and use it for the good of himself and others, instead of just jealously hoarding it. Spirituality brings the Heart back to the business man.

Now, I have this brilliant (if i may say so myself ) message for everyone. But to get it to you, i need a computer, i need internet (preferably broadband) access, i need to be able to host my blog, etc, all of which needs money… So for spirituality to spread, it needs the support of commerce. It needs wealth. Thus business becomes the Legs of Spirituality.

Business and Spirituality are intricately linked. They are married to each other. Don’t make the mistake of divorcing them! :)

Many people make the mistake of running after Laxmi (money)… Would anyone like it if someone else wooed their wife? You think Lord Narayana is going to be pleased if you go after His beloved wife?! :) They may even get the money, but that money only brings them pain of different flavours. What else do you expect if you piss off Her husband?! :)

The intelligent ones, they go after Lord Narayana Himself. They learn and practice Meditation… Go deeper into Spirituality, coz they know, if you have Him, then His wife has to follow! Where He is, she is! So Wealth and abundance come to these lucky, wise people and with Lord Narayana and Goddess Laxmi on their side, they become supremely happy and extremely comfortable as well

Deepawali is the Celebration of Abundance. Of Wealth. Of the Goddess Laxmi in all Her glory. But for this celebration to be complete, there has to be a deep, spiritual, meditative consciousness underlying it, otherwise its just pretty lights and loud noises.

This year, in between the sweets and the fireworks, meditate and do Pooja. Do some Seva and have a bit of Satsang.

Make this Deepawali a meaningful glorious Celebration for yourself and others around you.

 

We wish everyone a very, very Happy Deepawali and a fantastic, prosperous and meditative New Year!!!

Jai Gurudeva!

love

bawa (n dinesh)

PS: I did not post a direct link to their blog as their server is currently down. Will do it once its running again :)

comments: 2 » tags: