Friday, 28 February 2014

Creating first thread in java

Thread Creation:
Threads can be created either by,

  • Extending the java.lang.Thread Class or by

  • Implementing the Runnable interface



Example: Extending Thread class
package thread;
/**
* @author Sivaranjani D
*
*/
public class ExtendingThread {
public static void main(String args[]){
ThreadA thread = new ThreadA();
thread.setName("ThreadA");
//thread.run(); //turn on this and turn off the thread.start() and see the difference
thread.start();
System.out.println(Thread.currentThread().getName());
}
}

class ThreadA extends Thread{
public void run(){
for (int i=0; i<5;i++){
System.out.println("Executed by "+Thread.currentThread().getName()+" and output: "+i);
}
}

}

Output
main
Executed by ThreadA and output: 0
Executed by ThreadA and output: 1
Executed by ThreadA and output: 2
Executed by ThreadA and output: 3
Executed by ThreadA and output: 4

Explanation:

  1. Class ThreadA extends the java.lang.Thread class and it will override the run method

  2. The code inside the run method is the job which will be executed by thread when calling the start method on it

  3. Thread is instantiated in the main method by calling "ThreadA thread = new ThreadA();" . At this stage thread is not alive and it will be in new state.

  4. By default thread has name starts like "thread-1". This can be changed by calling the "setName(String name)" method on the thread instance.

  5. Calling start method on thread instance creates the new stack and thread is set to be alive at this stage. This state is called as runnable.

  6. The limitation of creating threads by extending Thread class is, here the job can be executed by only one thread.


Example:Implementing the Runnable Interface
package thread;
/**
* @author Sivaranjani D
*
*/
public class ImplementingRunnable {
public static void main(String args[]){
ThreadB job = new ThreadB();
Thread servant1 = new Thread(job,"Servant1");
servant1.start();

Thread servant2 = new Thread(job,"Srevant2");
servant2.start();
}
}

class ThreadB implements Runnable{
public void run(){
for(int i=0;i<5;i++){

System.out.println("Executed by "+Thread.currentThread().getName()+" and output: "+i);
}
}

}

Output
Executed by Servant1 and output: 0
Executed by Srevant2 and output: 0
Executed by Servant1 and output: 1
Executed by Srevant2 and output: 1
Executed by Servant1 and output: 2
Executed by Srevant2 and output: 2
Executed by Servant1 and output: 3
Executed by Servant1 and output: 4
Executed by Srevant2 and output: 3
Executed by Srevant2 and output: 4

Explanation:

  1. ThreadB implements Runnable interface, and it overrides the run method

  2. In the main method, instance of ThreadB is created which is of type runnable

  3. Create a thread instance and pass the runnable object inside the thread. [here the Thread(Runnable target) constructor is used]

  4. So the advantage here is, we can pass the job of one runnable object to multiple threads as given above. As you can see in the above example, servant1 and servant2 are 2 threads, which takes the runnable object as their constructor parameter. When we call run on each thread, each executes the same code inside run method separately.



Thread Constructors

  1. Thread() - Creates thread

  2. Thread(Runnable Target) - creates thread with the runnable object

  3. Thread (Runnable Target, String name) - Creates thread with the runnable object and sets the name to the thread

  4. Thread(name) - Creates a thread and sets the name to the thread


Important points:

  1. Once the run method finishes thread reaches the dead state.

  2. Calling start method on thread instance should be only once for the thread's life time. Second call of start method on the same thread causes the IllegalThreadStateException.

  3. The order of thread execution is not guaranteed always. That means the above order of thread execution will change for each execution. If you are not seeing the order change, then increase the loop to 400 and see.

Tuesday, 25 February 2014

Daemon Threads and User Threads in java

Daemon vs Non-Daemon threads:
Thread has two types, namely daemon threads and non-daemon threads (user threads). Daemon threads will run in background and JVM does not wait for the daemon threads to complete. In contrast JVM waits until all the non-daemon threads or user threads to complete.
By default the main thread is the non-daemon thread and any threads created by main thread will be a non-daemon thread because threads inherit its parent’s properties.
To convert user thread to a daemon thread use the following call in java,
threadName.setDaemon(“true”);

Example of Daemon threads: Garbage collector operation is done by daemon threads and it runs in background.
Code
package thread;
/**
* @author Sivaranjani D
*
*/
public class DaemonThreadExample {
public static void main(String args[]){
Thread t = new Thread(new Runnable() {

public void run() {
while(true){
System.out.println("Daemon thread is running");
}

}
});

t.setDaemon(true); // turn this off and on to see the difference
t.start();
System.out.println(Thread.currentThread().getName());
}
}

When you turn on the setDaemon to true, you can see only some 4 to five time the "Daemon thread is running" statement printing. Because while Daemon thread is running JVM don't wait and it terminates once the main non-daemon thread completes. But when you turn that off, the JVM never terminate and waits for the non ending loop of the non-daemon thread.

Monday, 24 February 2014

Java Stack and Heap

Stack:


In JVM each thread has a private stack created at the same time when a thread is created. It holds all the local variables and its results. When a main method is called main thread will be created by default and it will be always on the bottom of the stack. The methods invoked from main will be added further on the stack.
Package thread;
/**
* @author Sivaranjani D
*
*/
public class FirstThread  {
public static void main(String args[])throws Exception{
System.out.println("Current Thread :"+Thread.currentThread().getName());
}
}

Output:
Current Thread :main

But when a new thread is created, the method invocations by the thread will be started in a new stack. The execution of main thread and the newly created threads happen in parallel.when run method completes stack will be closed for that stack.

Thread Stack explained:

 

[caption id="attachment_433" align="alignnone" width="770"]java stack java stack[/caption]

Here concurrent means, whenever JVM gets a chance to execute inside a CPU (Single core systems), it acts as a mini-OS and schedule its threads internally.

The JVM specifications of different vendors permits either fixed sized stack or dynamically extendable/contractible stacks depends on their implementations.

Exceptions:

StackOverfloError, if a computation in a thread requires more than the permitted stack size.

HEAP:

JVM has a heap that is shared among all the instance and threads. It will be created on JVM start-up. Heap size can be extended or contracted based on the JVM specification. Once the computation is over the no longer used instances will be garbage collected.

Heap size can be increased with the JVM options -Xms and -Xmx.  Xms denotes starting size of Heap while -Xmx denotes maximum size of Heap in Java.

Exceptions:

When the computation requires more memory than allocated, OutOfMemory error is shown.

Saturday, 22 February 2014

java - explained from source code to execution

The java code undergoes multiple process before the final execution. The processes are,


  • Compilation

  • Loading

  • Linking

    • Verification

    • Preparation

    • Resolution



  • Execution



Compilation:


Compilation is performed by java compiler (javac.exe presents inside JDK/bin). It takes the source code (.java files) and creates the binary files called class files. The class files are the intermediate files which can be executed in any other Java run time machine independent of the Operating system.

Loading:


Loading is the process of finding the binary representation(class files) of the class/interface given the file name. The class loader is explained in detail here.

Linking


Once the classes are loaded into JVM linking starts and it is the process of verifying, preparing and resolving the classes and all it's references.
Verification:

This steps is to ensure that the class obeys for all semantics of the java language. For example it check the following




  •  The byte code is structurally correct

  • The destination of each go to is a byte code instruction

  • The stack will not overflow or iunderflow


Preparation

Here JVM allocates memory for all the variables and instances and prepares them for initialization. Here the variables are set with the default values. For example,  the variable 'int i=10' will be set with the value zero here instead of 10.
Resolution

This is the process of locating all the referenced classes, interfaces and variables and linking them with the direct references.

So to conclude,

  • Classes are compiled,

  • Loaded into JVM

  • verified

  • memory is allocated with the default values

  • references are linked


The final step will be initialization. Here the variables are set with the values declared.  So in the above example the value of "i" will be initialized with 10. After this steps JVM will perform the execution of the classes and gives the output.

Tuesday, 18 February 2014

Threads, Multiprocesser, Multitasking, Multithreading, Multi core systems

We often here some jargons in computer industry like multi-processor, multi-tasking, multi-core and multi-threading. So I thought of exploring what all these 'multi-'s and given it below for easy understanding.
Tip:
Find number of cores in windows OS : wmic cpu get NumberOfCores
Find number of processors in windows OS : systeminfo | find/i "processor(s)"

Multitasking:
This is the task of the underlying OS which is capable of doing multitasking with in the single/multiprocessor systems or single/multicore systems. The OS does multitasking with the help of Context switching(needed only in single core/single processor systems) and with some scheduling algorithms. Ex: Windows XP Operating system.

For example, consider the below image. Here  word, Mail etc... are called as an applications and each run as a separate processes. If you open the task manager in windows OS you can see them running as a process. The OS uses the schedulers and does context switching or schedule it in multiple core/processors. In a single core/processor at a time only one process will be running but when u invoke a new process the scheduler preempt the old and calls the new processor which gives the  feeling of all process running on a same time. In multiprocessor/multicore systems the process will be running parallel.

If the OS supports multitasking, then the only difference in  multicore/multiprocessor system is the performance. The multiple core/processor systems does not need to wait for a single processing unit which increases the performance.

[caption id="attachment_388" align="alignnone" width="300"]multitasking multitasking[/caption]

Multithreading:
In concurrent programming there are two basic units of execution, namely

  • Process

  • Thread


Thread is a smallest sequenced set of instructions in execution. There are native threads at OS level but java has it's own threads and JVM works as a min OS and schedules it's threads internally. In some situations java threads are mapped to native threads.

Process is an instance of computer program that is running and process can have multiple threads. So in the above example, if we take email application it is a single process. But in turn it can have multiple threads and each used for listening incoming messages or to send a mails or to search etc.. Programming in this was will enhance the application speed. If there is no threads then the email as a process will get very less chance to execute in the CPU, but if it has multiple threads then the chances of each thread getting CPU to do the part of the process's job will increase the performance of the application.

[caption id="attachment_394" align="alignnone" width="300"]multithreading multithreading[/caption]

Multicore & Single Core:
A multicore system is a single processor CPU but with two or more core and each core with it's one microprocessors for execution.  Some components of CPU like L1 Cache are duplicated for each core.

[caption id="attachment_387" align="alignnone" width="300"]multicore multicore[/caption]

In single core system, there will be one CPU and it contains only one core.

[caption id="attachment_386" align="alignnone" width="300"]single core single core[/caption]

Multiprocessor & Single processor:Multiprocessor system is a system with multiple CPU's (Central processing unit) whereas in Single processor system has only one CPU. Here the process/ threads will be scheduled to different processors and no context switching is required.

Friday, 7 February 2014

Eclipse - Shortcuts, automatic author name for new files and debugging

Shortcuts:




  • To create new files/project - Ctrl+Shift+N

  • To Search Files - Ctrl + Shift +R

  • Search a String in a file -  Ctrl+H and find file search on the tabs above and Enter the string, file type to be searched

  • Search method name in a class- Ctrl+0

  • Replace/Find String in a file - Ctrl+F

  • To run a program - Ctrl+F11



Author name in newly Created Files:




  • Go to Window-->Preferences-->in the search box type code template and expand the code. Now Select New Java Files and click Edit

  • Enter the following in the box, save and then close


  • ${filecomment}
    ${package_declaration}
    /**
    * @author ${user}
    *
    */
    ${typecomment}
    ${type_declaration}



Debugging:


Debugging with web logic Server:




  • Go to your weblogic domain(ex: C:\Oracle\Middleware\user_projects\domains\<domainname>) -->bin and find set SAVE_JAVA_OPTIONS=%JAVA_OPTIONS%

  • Replace the above line with, set SAVE_JAVA_OPTIONS=%JAVA_OPTIONS% -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=4000,server=y,suspend=n

  • Go to eclipse, on the top right side corner select the debug perspective as below



[caption id="attachment_368" align="aligncenter" width="591"]eeclipse perspective eeclipse perspective[/caption]

  •  Now click on debug and select configurations as below.


[caption id="attachment_369" align="aligncenter" width="652"]debug configuraion debug configuraion[/caption]

  • Enter the configuration details as below and click debug.


new configuration

 

  • Now the application is enabled with remote debugging. We can add breakpoints in the code and when you run the app press f6 to go line by line. And press f5 for method definition.

jquery draggable jumping effect issue on firefox

Problem:
Jquery draggable is an awesome feature used to drag the elements around the page. But it irritates some times with the jumping effect and positioning issues on the Firefox. There are lots of fix provided over internet but when you apply them it breaks in other browsers like chrome.The jumping issue may also happens while resizing.

The issues are already reported here.

Solution1 - normal jumping effect:
Based on the solution provided here, I am reimplementing the code to work with both chrome and Firefox. The given code fixes the problem with Firefox. But again when comes back to chrome it fails. So I added one condition so that this patch will be called only for Firefox browsers. Also the body position attribute is changed to relative for Firefox.

Create a file name patch_draggable.js and copy the below code inside.
Code:
function monkeyPatch_mouseStart() {
// don't really need this, but in case I did, I could store it and chain
var oldFn = $j.ui.draggable.prototype._mouseStart ;
$j.ui.draggable.prototype._mouseStart = function(event) {var o = this.options;function getViewOffset(node) {
var x = 0, y = 0, win = node.ownerDocument.defaultView || window;
if (node) addOffset(node);
return { left: x, top: y };function getStyle(node) {
return node.currentStyle || // IE
win.getComputedStyle(node, "");
}
function addOffset(node) {
var p = node.offsetParent, style, X, Y;
x += parseInt(node.offsetLeft, 10) || 0;
y += parseInt(node.offsetTop, 10) || 0;if (p) {
x -= parseInt(p.scrollLeft, 10) || 0;
y -= parseInt(p.scrollTop, 10) || 0;if (p.nodeType == 1) {
var parentStyle = getStyle(p)
, localName   = p.localName
, parent      = node.parentNode;
if (parentStyle.position != "static") {
x += parseInt(parentStyle.borderLeftWidth, 10) || 0;
y += parseInt(parentStyle.borderTopWidth, 10) || 0;

if (localName == "TABLE") {
x += parseInt(parentStyle.paddingLeft, 10) || 0;
y += parseInt(parentStyle.paddingTop, 10) || 0;
}
else if (localName == "BODY") {
style = getStyle(node);
x += parseInt(style.marginLeft, 10) || 0;
y += parseInt(style.marginTop, 10) || 0;
}
}
else if (localName == "BODY") {
x += parseInt(parentStyle.borderLeftWidth, 10) || 0;
y += parseInt(parentStyle.borderTopWidth, 10) || 0;
}

while (p != parent) {
x -= parseInt(parent.scrollLeft, 10) || 0;
y -= parseInt(parent.scrollTop, 10) || 0;
parent = parent.parentNode;
}
addOffset(p);
}
}
else {
if (node.localName == "BODY") {
style = getStyle(node);
x += parseInt(style.borderLeftWidth, 10) || 0;
y += parseInt(style.borderTopWidth, 10) || 0;

var htmlStyle = getStyle(node.parentNode);
x -= parseInt(htmlStyle.paddingLeft, 10) || 0;
y -= parseInt(htmlStyle.paddingTop, 10) || 0;
}

if ((X = node.scrollLeft)) x += parseInt(X, 10) || 0;
if ((Y = node.scrollTop))  y += parseInt(Y, 10) || 0;
}
}
}

//Create and append the visible helper
this.helper = this._createHelper(event);

//Cache the helper size
this._cacheHelperProportions();

//If ddmanager is used for droppables, set the global draggable
if($j.ui.ddmanager)
$j.ui.ddmanager.current = this;

/*
* - Position generation -
* This block generates everything position related - it's the core of draggables.
*/

//Cache the margins of the original element
this._cacheMargins();

//Store the helper's css position
this.cssPosition = this.helper.css("position");
this.scrollParent = this.helper.scrollParent();

//The element's absolute position on the page minus margins
this.offset = this.positionAbs = getViewOffset(this.element[0]);
this.offset = {
top: this.offset.top - this.margins.top,
left: this.offset.left - this.margins.left
};

$j.extend(this.offset, {
click: { //Where the click happened, relative to the element
left: event.pageX - this.offset.left,
top: event.pageY - this.offset.top
},
parent: this._getParentOffset(),
relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
});

//Generate the original position
this.originalPosition = this.position = this._generatePosition(event);
this.originalPageX = event.pageX;
this.originalPageY = event.pageY;

//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

//Set a containment if given in the options
if(o.containment)
this._setContainment();

//Trigger event + callbacks
if(this._trigger("start", event) === false) {
this._clear();
return false;
}

//Recache the helper size
this._cacheHelperProportions();

//Prepare the droppable offsets
if ($j.ui.ddmanager && !o.dropBehaviour)
$j.ui.ddmanager.prepareOffsets(this, event);

this.helper.addClass("ui-draggable-dragging");
//JWL: Hier vindt de jump plaats
this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position

//If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
if ( $j.ui.ddmanager ) $j.ui.ddmanager.dragStart(this, event);

return true;

};

}
if($.browser.mozilla) {
monkeyPatch_mouseStart();
$("body").css("position", "relative");

}

Call this after calling jquery.min and jquery.ui.min as given below,
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-ui.min-1.10.2.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/patch_draggable.js"></script>

Solution2 : jumping at the time of resizing

After putting the above fix the jumping effect I faced in chrome. So the solution is reset the position after the element is re sized.

Code:


$j( "#draggablecorrect" ).resizable({start: function(event, ui) {
$j( "#draggablecorrect" ).css({
position: "relative !important",
top: "0 !important",
left: "0 !important"
});
},
stop: function(event, ui) {
$j( "#draggablecorrect" ).css({
position: "",
top: "",
left: ""
});
}
});

Wednesday, 5 February 2014

jquery draggable, droppable and resizable

Jquery is a fast and light weight java script library. It provides API to do easy UI changes, animation, ajax calls and etc. Also it provide support to most of the web browsers.
In this post, I will explain the most interesting functionalists of jquery called draggable, droppable and resizable.  As an interesting example I am creating an image hotspot and capturing it's co-ordinates using these technologies.

Prerequisites:
Download the following.
 http://code.jquery.com/jquery-1.10.2.min.js
http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js
http://technicalminds.in/wp-content/uploads/2014/02/monkey-150x150.jpg

Steps:

  • Create a folder named "jquery examples".

  • Copy the above downloaded files inside that.

  • Create a file named jquerydraganddrop.html and copy the belowcode.



<doctype>
<meta charset="utf-8" />
jQuery UI Draggable - Default functionality<style><!--
#minblock { width: 1000px; height: 500px; }
#draggablecorrect { width: 50px; height: 50px;  float: right; margin: 0 600px 0 0; }
#draggablewrong { width: 50px; height: 50px;  float: right; margin: 0 600px 0 0; }
#droppable { width: 350px; height: 350px;  }
--></style>    <link href="jquery-ui.css" rel="stylesheet" /><script type="text/javascript" src="jquery-1.10.2.min.js"></script><script type="text/javascript" src="jquery-ui.min-1.10.2.js"></script>
<div></div>
<div id="minblock" style="border: 1px solid #000;">
<div id="droppable" style="border: 1px solid #000; width: 350px; height: 350px; padding: 0.5em; float: left; margin: 10px;"><img id="hotspotimage" alt="" src="monkey-150x150.jpg" width="350" height="350" /></div>
<div id="hotspot">
<div id="draggablecorrect" style="border: 1px solid #000;">Correct<img id="correctspot" alt="" src="sign_correct.gif" /></div>
</div>
<script type="text/javascript">// <![CDATA[
$(function() {
$( "#draggablecorrect" ).resizable();
$( "#draggablecorrect" ).draggable({ revert: "invalid" });$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this ).addClass( "ui-state-highlight" );
var pos = ui.draggable.offset(), dPos = $(this).offset();
alert("Top: " + (pos.top - dPos.top) +
", Left: " + (pos.left - dPos.left));}
});$('#hotspotimage').click(function(e) {
var posX = $(this).offset().left, posY = $(this).offset().top;
alert((e.pageX - posX)+ ' , ' + (e.pageY - posY));
});});
// ]]></script></pre>



  • Save the code and run it with your preferred browser.

  • The output looks like below. The correct box can be dragged and you can create hotspot on the monkey image. Also the box is resizeable.


[caption id="attachment_329" align="alignnone" width="650"]draganddrop draganddrop[/caption]

Source code:


Download.


Common Issues:
There may be jumping issues while using the CSS attributes like margin and positioning.
If you encounter the same please check the below links.
Jumping issues on browsers