Thursday 25 November 2010

Maven manages project dependencies

I'm pleased with Maven today.

My product uses apache common-net jar. I wanted to make some changes in the common-net source for some testing purpose. So I took the source from internet. Common-net is built using maven. I could make it out by the presence of pom.xml and I understood that this is going to reduce my work effectively.

What I did is -
1) I took the source code and at the same location I ran the following -
mvn eclipse:eclipse

This creates eclipse project setting files.

2) I created eclipse project on the same common-net source code location and modified the class I wanted to and ran the build by typing -
mvn clean install

It created the new jar in the target folder.

How easy it is to manage project dependecies with maven! Otherwise I'd have had to download all the dependencies manually. Thanks maven :)

Wednesday 13 October 2010

test syntax-highlighter

something at the start


public class HelloBlogger {
public static void main(String [] args) {
System.out.println("Hello Blogger!!");
}
}

something more at the end


Check this link - link

Sunday 22 August 2010

Tomcat on 64bit Windows vista

I was not able to run tomcat on my windows vista, I thought the reason was vista. But no; the issue was 64 bit system. Apcahe has provided different tomcat.exe files for 64 bit system.

We can get them from http://svn.apache.org/repos/asf/tomcat/tc6.0.x/tags/TOMCAT_6_0_20/res/procrun/

To get tomcat running on 64 bit system, We can follow the steps as given here http://stackoverflow.com/questions/211446/how-to-run-tomcat-6-on-winxp-64-bit

I didn't need to create/edit key in registry. It worked only by replacing exe files with those for 64 bit.

Now I can work on tomcat even on my laptop. :)

Thursday 22 July 2010

Rhino - Part2 - Scope Sharing/Parent Scope

As specified in this post, you don't need to create a scope from scratch.
A scope object can be created using already existing scope where already existing scope behaves like a parent scope.

E.g. localScope object can be created using globalScope, so that local scope can inherit global scope.
This can be done as follows –
Scope localScope = context.newObject(globalscope, );
where constructor_name = name of the constructor which will be used in order to create the scope. This constructor definition is present in globalscope.

If global scope has been shared among different local scope objects, then if global scope changes due to execution of any script using any of the local scopes, then this change is reflected in all the local scopes.
e.g. suppose, G = global scope, L1, L2 = local scopes derived from G.
S1 and S2 are the script objects.
Say, “a” is a global variables value of which is 5.
If on S1.execute(cx,L1), a becomes 10, then this change gets reflected in both L1 and L2.

If we don’t need this change to be reflected in all the other local scopes, then we can do following –
L1.setPrototype(G);
L1.setParentScope(null)

This creates a clone of G for L. And setting parent scope to null removes the parent scope. (This whole shifts the role of global scope from parent scope to prototype). This is called prototype-based inheritance. Check Proototype based programming.

Rhino API - Introduction

Use: To execute Javascript from java classes.

How Rhino achieves it -
To execute any code what all needed is the context i.e. call stack, local registers etc and the scope which contains all lookup variables and functions. Source gets compiled to produce object files. And object files are used for execution. Rhino uses the same concept for Javascript execution.

Steps:
1) Create Context (Context cx = Context.enter())
2) Initialize scope (Scriptable scope = cx.initializeStandardObjects())
3) Populate scope(scope.put(name,value))
4) Compile the script (Script script = cx.compileScript(String scriptSource)
5) Execute the script (script.execute(cx,scope))

Context = It represents runtime context which contains all the information for execution of javascript.
Scope = it contains standard variables, functions, their definitions which are looked up while execution of javascript.
Script = It is an output of compilation of javascript. (Like a .class file for java class)

Check this.

Thursday 24 June 2010

How to deep copy an object whose structure is defined at runtime?

My application needed to make a deep copy of an object, type of which was defined at runtime. It is a complex object like map which had still more complex objects inside it.

The simplest solution to do this is to serialize the object in memory using ByteArrayOutputStream instead of using FileOutputStream.
Then deserialize it using ByteArrayInputStream instead of using FileInputStream. The final object that you get is the deep copy of your object.

But the main constraint is it needs the object to be serializable.

Wednesday 5 May 2010

JVM and GC

I got training on JVM. Few words about it.

Every Java Programmer knows java virtual machine. It translates the bytecode (which is generated by java compiler) into machine instructions and executes them.
JVM makes java portable anywhere i.e. platform independent.

JDK used to be very slow till 1.2 because of caching of instruction set and no optimization of it.
From JDK 1.3, it became faster. Why? JVM included hotspot technology.
This hotspot developed by Oracle Corporation, has many optimizing techniques that made java to execute faster. Few of these techniques are -
1) Loop unrolling – e.g. it unrolls a for loop by copying the statements inside loop n number of times where n is the number of times for which for loop is going to be run. This avoids the use of counters. If you do not have counters during iterations. You do not have to spend time in reading, incrementing and writing them back. So this technique makes execution of loop faster.
2) Method inlining
3) Flow rearranging
4) Efficient garbage collection algorithms

Java Hotspot has 2 types of VMs –
1) Java HotSpot Client VM – During start up of an application, this VM loads only those classes which are required at start up. It loads other classes lazily (when required). This reduces start up time of an application but decreases the performance.

2) Java HotSpot Server VM – This is opposite. It loads all the classes at the start up and improves performance.

You can use the option -server or - client during execution of your application to enable respective hotspot VM.
Java HotSpot Client and Java HotSpot Server compilers translate bytecode to machine instructions.

*****

Now something about Garbage Collector.
GC is part of JVM. Hotspot technology highly improved its performance.
But what does garbage collector do?
It collects and destroys the garbage of java which is collection of dead objects or unreferenced objects.

How does it come to know whether some object is to be removed or not?
It uses root set. Some basic information about root set is present here.



This root set is the set of those objects which have direct reference from JVM and not from some other object. E.g. object A was referenced directly by JVM. So any object say B which has its reference present inside object A is called an indirectly referenced object. This need not to be part of root set because JVM knows about it via object A. When JVM sees that object A is not referred anywhere in the program, it destroys A as well as B (unless B is also referred inside some other object or it is part of root set.) GC keeps checking for each object inside root set and destroys objects which have no direct or indirect references.)
This is how GC works with the help of root set.

Can we call GC explicitly in our program anywhere we want?
Yes. System.gc(); will do it.

You can see the GC output by executing your application with option –verbosegc.
e.g. java –verbosegc Test

GC works like a simple single threaded program or like multithreaded program. In multithreaded way, it improves the performance of program execution.

Some GC algorithms that were introduced by hotspot technology:
1) Sweeping GC:



It simply removes the object from the memory and frees the memory. Whenever next object is born, that will be placed at free location.

2) Compacting GC:



It is bit more advanced than sweeping GC but still simple. After freeing the memory, it gathers all the objects at one place in the memory, so to avoid memory leaks which are possible in sweeping GC.

3) Copying GC. – This is something interesting. It is bit complex and is assumed to be the most efficient GC algorithm if there is very much to clean at a time.



It divides memory heap into active and inactive regions. Whenever an object is created it gets space in active region. After freeing the active region during GC call, it copies the existing objects in inactive region. And this inactive region becomes active region and vice-versa. This is useful when you want to clean large number of objects and need to keep only few.

To understand this algorithm in better way we need to know that there are 2 types of memory heaps
[*In Java, all the objects are located inside memory heap and their references are present in method stacks. By the way, an object present in memory heap can carry a reference to any other object.]
1) Monolithic heap – It is as simple as a cupboard which has no shelf.

2) Generational heap –



From the diagram we can see that there are 2 main regions –
a) New object area – this has 3 divisions – new EDEN, survivor space 1 and 2
b) Old object area
New object area has application of copying GC.
Once EDEN + survivor space 1 = active region and survivor space 2 = inactive region.
And then after next iteration of GC EDEN + survivor space 2 = active region and survivor space 1 = inactive region.
It goes on. This GC is called minor GC.
(This is for the scenarios when objects get created in large number as well as destroyed in large numbers. This is for short living objects. E.g. transaction related or some use case related objects in an enterprise application.)

Old object area can have application of any of sweeping and compacting GC algorithms. This GC is called major GC.
(This is for the scenario when objects are created once and then are deleted much more later. i.e. this is for long living objects. E.g. start up objects which born on server start up and die when server shuts down.)

In case of long living objects, sweeping or compacting GC results in efficient algorithm as they are less complex.

When an object is triggered to be an old object?
There are 2 triggers that we can configure with command line parameters.
a) By counter - an object which lives for more than say n iterations of copying GC is moved to old object area.
b) By percentage. – say when n% of SP1 becomes full, m% of it is moved to old object area. (Older objects are preferred.)

When is GC called by JVM?
We can configure this duration in command line parameters.

Check this for command line parameters.

Of course there is lot more information on it.

Thursday 15 April 2010

Should BufferedWriter have open()?

An object of BufferedWriter class has a parameterized constructor which takes an object of FileWriter Class. With this it becomes a handler to the file which FileWriter’s object corresponds to.

This handler has functions like write(), flush() and close(). Initially I was under impression that there must be an open() function too - To open the connection to the same file again. But it is not present.

I wondered - why is it not present? If it can close the connection, it should be able to open it again. But it is not.

Then my question changed to - Why should it be present first of all?
To open the closed file if we need it somewhere after closing it.

And then what is the purpose of closing the connection?
We close it so that the file will be freed to delete, to move or to do anything on it i.e. for the file to get rid of its handler.

What if it was present?
After closing the connection how would it find the file which it has to connect to? And suppose your handler kept the details of file with itself in order to open the same file again. But again in meantime when it was disconnected from the file, if someone moved file to some different location, how would you rely on old information? Or you are making handler to keep following the file until handler is alive? Then how will the file get rid of the handler?

Anyway, to open the already closed file and to append data to it, you have ‘append’ option in the constructor of FileWriter.

Sunday 14 March 2010

Multithreading

Creation of thread/child process:
In java, whenever you start the thread (thread.start()), a new child process i.e. a thread gets created and there multithreading/multiprocessing starts.

This is wrong. It is not a child process. It is a thread. And it is not multiprocessing. It is multithreading. [This was added later.]

To implement it in Java there are 2 options:
1) Extend thread class by your class say myThread.
2) Implement the run method.
3) Create object of myThread.
4) With this object call the start method.

The other option is:
1) Implement the interface runnable
2) Implement the method run()
3) Pass the object of this class to the constructor of Thread class and create the thread class’s object.
4) Call the start method with the object of thread class.


To implement this in C,
Fork() procedure is used.
fork() spawns the child process from parent. The child process has the same attributes as that of parents except process id. Both run concurrently.

Consider an example is as follows –
Say you have an attribute called newProcID in the parent procedure.
newProcID = fork();
fork() creates the child process and returns 2 IDS to 2 processes. Parent process gets the ID of the child process and child process gets the newProcID = 0. As a child process has the same attributes as that of the parent, it also gets the newProcID attribute and hence,

the code in the parent process –
newProcID = fork();
If (newProcID == 0)
Newfunction(); // this part will be executed in child process
Else
childID = newProcID; // this part will be executed in parent process.

Now some difference in java and C implementation by memory point of view:
When we call fork() method in C, it spawns the child process. The address space of parent gets copied. Both child and parent process have identical address spaces but at different address locations. So whatever attributes( variables and their values) parent process has , same the child process has. You can access the attributes of the parent process in the child process.
But in Java, when we call start method of thread, it spawns the child process/thread and then it runs the run method of that thread class. (The class that extends thread class).
Run() method can access attributes of only the class by object of which we invoked start method and hence may not have the parent class’s attributes. It means in Java, it does not copy the whole memory stack for child process. Instead it creates new memory stack. So child cannot access the parent’s attributes.
This is all what I understand from how the implementation goes in both the languages. I’m not sure about what I have written about memory management in Java. Still trying to find the answer.

This is again wrong. Whatever implementation in Java I have talked about is of multithreading. And what I have talked about in C is of multiprocessing. So the difference which I have indicated here is between multithreading and multiprocessing not between what Java provides and what C provides.

Sunday 14 February 2010

tomcat installation

After several attempts of installing tomcat, i tried editing my temp variables to C:/temp as given in this link. And it worked for XP. But not working for Vista. Still trying. :(

Wednesday 20 January 2010

Subtitles editor

Yippee!
I got a software to edit subtitles - here

I took the first one (Aegisub) and installed it.

I wanted to shift the time of subtitles forward by 20 Seconds. It is pretty simple.
Just open the file with Aegisub and click on "Open Shift Times Dialogue" - the icon on toolbar with the pic of an arrow and a vertical stripe. Enter the required values.
:)

Now I can watch any movie with better understanding. \0/

By the way, if you have a movie without subtitles, then search for subtitle file of that movie on internet. Some of them have .srt extension. (I used the same.) There can be .sup too. I don't know what the difference is. But .srt worked for me.
Take the file. Rename it with the same name as that of your movie file name. (keep the extension as .srt; don't change that).
Keep both the movie file and srt file in the same folder.
Open your movie player. I used VLC player. In that, select Video menu-> Subtitles Track -> Track 1.
It should work. (You might need to restart the VLC player.)

Saturday 16 January 2010

Behavior of "inherited protected" variable in Java

Something to remember before going ahead –
There are 2 basic aspects of a variable– inheritance (can be inherited or not; with values – yes/no) and access (can be accessed or not; with values – default/public/private - ignore protected for now)

Consider 2 scenarios:
Scenario 1:

As shown in the above figure –
Result is -
B inherits x, C can access x through object of A and through object of B both.
D inherits x.
E cannot access x at all.

Scenario 2:

As shown in the above figure –
Result is:
B, C inherit x.
Class D cannot access x at all.

Conclusion:
This is about variable x of B.
When protected variable is inherited inside package (Scenario 1), it behaves like default for access and yes for inheritance.
When protected variable is inherited outside package (Scenario 2), it behaves like private for access and yes for inheritance.

Thus, the table is as follows - (click on the table image)

Tuesday 12 January 2010

When you want to carry your heavy laptop

For those who didn’t know if we can remove the battery of laptop, we can remove it and can reduce its weight. This is if we can use it like a computer (i.e. with electric cable always plugged in laptop). Just find how you can remove the battery and reduce the weight of your bag. I could do it for my hp laptop. Now it is easy for me to carry my laptop every weekend to Mumbai. Yippee!