Tuesday, 20 January 2015

What is sleep() method in Thread Class

Sleeping a thread (sleep() method):

The sleep() method of Thread class is used to sleep a thread for the specified time.

Syntax of sleep() method:

The Thread class provides two methods for sleeping a thread:

public static void sleep(long miliseconds) throws InterruptedException
public static void sleep(long miliseconds, int nanos) throws InterruptedException


Example of sleep method:

class Test extends Thread{
public void run(){
for(int a=1;a<6;a++){
try{
Thread.sleep(500);
}
catch(InterruptedException ex){
System.out.println(ex);
}
System.out.println(a);
}
}
public static void main(String []args){
Test t1=new Test();
Test t2=new Test();
t1.start();
t2.start();
}
}

Output:
1
1
2
2
3
3
4
4
5
5
6
6

As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the thread shedular picks up another thread to run and so on.

Can we start a thread twice ?

No. After staring a thread,it can never be started again.If you does so, an IllegalThreadStateException is thrown.
For Example:

class Test extends Thread{
public void run(){
System.out.println("this is run method");
}
public static void main(String []args){
Multi t1=new Multi();
t1.start();
t1.start();
}
}

Output: this is run method
Exception in thread "main" java.lang.IllegalThreadStateException


What if we call run() method directly instead start() method ?

Each thread starts in a separate call stack.
Invoking the run() method from main thread,the run() method goes onto the current call stack rather than at the beginning of a new call stack.

class Test extends Thread{
public void run(){
System.out.println("this is run method");
}
public static void main(String []args){
Test t1=new Test();
t1.run();  //fine it will run , but does not start a separate call stack
}
}

Output: this is run method

Problem if you direct call run() method:

class Test extends Thread{
public void run(){
for(int a=1;a<6;a++){
try
{
Thread.sleep(500);
}
catch(InterruptedException ex){
System.out.println(ex);}
System.out.println(a);
 }
}
public static void main(String []args){
Test t1=new Test();
Test t2=new Test();
t1.run();
t2.run();
}
}

Output:
1
2
3
4
5
1
2
3
4
5
6


Note: As you can see in the above program that there is no context-switching because here t1 and t2 will be treated as normal object not a thread object.





What are the Methods of Thread Class

The join() method:

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop
executing until the thread it joins with completes its task.

Syntax:

public void join() throws InterruptedException
public void join(long miliseconds) throws InterruptedException

For Example:

class Test extends Thread{
public void run(){
for(int a=1;a<=6;a++){
try{
Thread.sleep(500);
}catch(Exception ex){
System.out.println(ex);
}
System.out.println(a);
}
}
public static void main(String []args){
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
t1.start();
try{
t1.join();
}catch(Exception ex){
System.out.println(ex);
}
t2.start();
t3.start();
}
}

Output:
1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
6
6

As you can see in the above example,when t1 completes its task then t2 and t3 starts executing.

Example of join(long miliseconds) method:

class Test extends Thread{
public void run(){
for(int a=1;a<=5;a++){
try{
Thread.sleep(500);
}catch(Exception ex){System.out.println(ex);}
System.out.println(i);
}
}
public static void main(String []args){
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
t1.start();
try{
t1.join(1500);
}
catch(Exception ex){
System.out.println(ex);}
t2.start();
t3.start();
}
}

Output:
1
2
3
1
4
1
2
5
2
3
3
4
4
5
5


In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts executing.

getName(), setName(String) and getId() method of Thread class:

public String getName()
public void setName(String name)
public long getId()

class Test extends Thread{
public void run(){
System.out.println("this is run method");
}
public static void main(String []args){
Test t1=new Test();
Test t2=new Test();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
System.out.println("id of t1:"+t1.getId());
t1.start();
t2.start();
t1.setName("Vishwa Singh");
System.out.println("After changing name of t1:"+t1.getName());
}
}

Output: Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
this is run method
After changling name of t1:Vishwa Singh
this is run method


The currentThread() method:

The currentThread() method returns a reference to the currently executing thread object.
Syntax:

public static Thread currentThread()

Example of currentThread() method:

class Test extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String args[]){
Test t1=new Test();
Test t2=new Test();
t1.start();
t2.start();
}
}

Output: Thread-0
Thread-1


Priority of a Thread (Thread Priority):

Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread
schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not
guaranteed because it depends on JVM specifification that which sheduling it chooses.

3 constants defined in Thread class:

1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.

Example of priority of a Thread:

class Test extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
Test t1=new Test();
Test t2=new Test();
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}

Output: running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1


Monday, 19 January 2015

What is Daemon Thread in Java

Daemon Thread:

There are two types of threads user thread and daemon thread. The daemon thread is a service provider thread. It provides services to the user thread. Its life depends on the user threads i.e. when all the user threads dies, JVM terminates this thread automatically.

Points to remember for Daemon Thread:

It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
Its life depends on user threads.
It is a low priority thread.

Why JVM termintates the daemon thread if there is no user thread remaining ?

The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.

Methods for Daemon thread:

The java.lang.Thread class provides two methods related to daemon thread

public void setDaemon(boolean status): is used to mark the current thread as daemon thread or user thread.
public boolean isDaemon(): is used to check that current is daemon.

Example of Daemon thread:

class Test extends Thread{
public void run(){
System.out.println("Name: "+Thread.currentThread().getName());
System.out.println("Daemon: "+Thread.currentThread().isDaemon());
}
public static void main(String []args){
Test t1=new Test();
Test t2=new Test();
t1.setDaemon(true);
t1.start();
t2.start();
}
}

Output:Name: thread-0
Daemon: true
Name: thread-1
Daemon: false


Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.

class Test extends Thread{
public void run(){
System.out.println("Name: "+Thread.currentThread().getName());
System.out.println("Daemon: "+Thread.currentThread().isDaemon());
}
public static void main(String []args){
Test t1=new Test();
Test t2=new Test();
t1.start();
t1.setDaemon(true);  //will throw exception here
t2.start();
}
}

Output: exception in thread main: java.lang.IllegalThreadStateException

What is Thread Schedular

Thread Schedular 

The thread scheduler is the part of the JVM that decides which thread should run.
There is no guarantee that which runnable thread will be chosen to run by the thread schedular.
On.ly one thread at a time can run in a single process.
The thread schedular mainly uses preemptive or time slicing scheduling to schedule the threads.

What is the difference between preemptive scheduling and time slicing ?

Under preemptive scheduling , the highest priority task executes until it enters the waiting or dead states or
a higher priority task comes into existence. Under time slicing , a task executes for a predefined slice of timeand then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

What is Multitasking in Java

Multitasking:

Performing multiple task at the same time is know as Multitasking.

How to perform single task by multiple threads ?

If you have to perform single task by many threads, have only one run() method.
For example:
>1. Program of performing single task by multiple threads.

class Test extends Thread{
public void run(){
System.out.println("this is task one");
}
public static void main(String args[]){
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
t1.start();
t2.start();
t3.start();
}
}

Output: this is task one
        this is task one
        this is task one

       
>2. Program of performing single task by multiple threads.

class Test implements Runnable{
public void run(){
System.out.println("this is task one");
}
public static void main(String []args){
Thread t1 =new Thread(new Test());  //passing annonymous object of Test class
Thread t2 =new Thread(new Test());
t1.start();
t2.start();
 }
}   

Output: this is task one
        this is task one


Note: Each thread run in a separate callstack.   

How to perform multiple tasks by multiple threads (multtasking in multithreading) ?   

If you have to perform multiple tasks by multiple threads,you have to use multiple run() methods.
For example:
>1. Program of performing two tasks by two threads:

class Test1 extends Thread{
public void run(){
System.out.println("this is task one");
}
}
class Test2 extends Thread{
public void run(){
System.out.println("this is task two");
 }
}
class Test{
public static void main(String []args){
Test1 t1=new Test1();
Test2 t2=new Test2();
t1.start();
t2.start();
 }
}

Output: this is task one
        this is task two

       
Same example as above by annonymous class that extends Thread class:

>2. Program of performing two tasks by two threads

class Test{
public static void main(String []args){
Thread t1=new Thread(){
public void run(){
System.out.println("this is task one");
 }
};
Thread t2=new Thread(){
public void run(){
System.out.println("this is task two");
}
};
t1.start();
t2.start();
}
}

Output: this is task one
        this is task two


Same example as above by annonymous class that implements Runnable interface:       

>3. Program of performing two tasks by two threads

class Test{
public static void main(String []args){
Runnable r1=new Runnable(){
public void run(){
System.out.println("this is task one");
}
};
Runnable r2=new Runnable(){
public void run(){
System.out.println("this is task two");
}
};
Thread t1=new Thread(r1);
Thread t2=new Thread(r1);
t1.start();
t2.start();
}
}

Output: this is task one
       this is task two
      

      
Next---> What is Thread Schedular in Java
       
       
       

How to create Thread in Java


In java there are two ways,you can create a thread:

>1. By extending Thread class
>2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and  implements Runnable interface.

Commonly used Constructors of Thread class:

Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)

Note: If you want to see how many methods,constructors and variables in a class or interface then you just type below commnad on CMD.

     i.e. javap whole_package_name.Class_Name. 
     //  javap java.lang.Thread
     // javap java.lang.Runnable

   
Commonly used methods of Thread class:

>1. public void run(): is used to perform action for a thread.
>2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
>3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
>4. public void join(): waits for a thread to die.
>5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
>6. public int getPriority(): returns the priority of the thread.
>7. public int setPriority(int priority): changes the priority of the thread.
>8. public String getName(): returns the name of the thread.
>9. public void setName(String name): changes the name of the thread.
>10. public Thread currentThread(): returns the reference of currently executing thread.
>11. public int getId(): returns the id of the thread.
>12. public Thread.State getState(): returns the state of the thread.
>13. public boolean isAlive(): tests if the thread is alive.
>14. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.
>15. public void suspend(): is used to suspend the thread(depricated).
>16. public void resume(): is used to resume the suspended thread(depricated).
>17. public void stop(): is used to stop the thread(depricated).
>18. public boolean isDaemon(): tests if the thread is a daemon thread.
>19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
>20. public void interrupt(): interrupts the thread.
>21. public boolean isInterrupted(): tests if the thread has been interrupted.
>22. public static boolean interrupted(): tests if the current thread has been interrupted   


Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().

Note: Runnable interface is also know as functional interface.(A interface which has only one method)

public void run():  is used to perform action for a thread.

Starting a thread:

start()  method of Thread class is used to start a newly created thread. It performs following tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.

>1. Creating thread By extending Thread class:

class Test extends Thread{
public void run(){
System.out.println("thread is in running state");
}
public static void main(String []args){
Test t=new Test();
t.start();
 }
}

Ouput: thread is in running state

Who makes your class object as thread object ?

Thread class constructor allocates a new thread object.When you create object of Test class,your class constructor is invoked(provided by Compiler) from where Thread class constructor is invoked(by super() as first statement).So your Test class object is thread object now.

>2. Creating thread By implementing the Runnable interface:

class Test implements Runnable{
public void run(){
System.out.println("thread is in running state");
}
public static void main(String []args){
Test t=new Test();
Thread th =new Thread(t);
th.start();
 }
}

Output: thread is in running state

Note: If you are not extending the Thread class, your class object would not be treated as a thread object.So you need to explicitly create  Thread class object.We are passing the object of your class that implements Runnable so that your class run() method can execute.


 Next---> What is Multitasking in Java

What is life cycle of a Thread in Java

Life cycle of a Thread:

A thread can be in one of the five states in the thread.According to sun, there is only 4 states new, runnable, non-runnable and terminated.
There is no running state. But for better understanding of the threads, we are explaining it in the 5 states. The life cycle of the thread is controlled by JVM.  The thread states are given below:

>1. New
>2. Runnable
>3. Running
>4. Non-Runnable (Blocked)
>5. Terminated

>1. New:

A thread is in new state if you create an instance of Thread class but before the invocation of start() method
i.e. Thread th=new Thread();

>2. Runnable:

The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
i.e. th.start();

>3. Running:

The thread is in running state if the thread scheduler has selected it means run() method call on that thread.
i.e. th.start();
     th.run();
   
>4. Non-Runnable (Blocked):

This is the state when the thread is still alive, but is currently not eligible to run.It is in blocked state or sleep or wait or in suspend state.
i.e. th.wait();

>5. Terminated:

A thread is in terminated or dead state when its run() method exits means on calling destroy() method
i.e. th.destroy();

Next--->How to create Thread in Java
   

What is Multithreading in Java

Multithreading in Java:

Multithreading is a process of executing multiple threads simultaneously.Thread is basically a lightweight subprocess, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than mulitprocessing because threads share a common memory area. They don't allocate separate memory area so save memory, and contextswitching between the threads takes less time  than processes. Multithreading is mostly used in games, animation etc.

Multitasking:

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:

>1. Process-based Multitasking(Multiprocessing)
>2. Thread-based Multitasking(Multithreading)

>1.Process-based Multitasking (Multiprocessing)

Each process have its own address in memory i.e. each process allocates seprate memory area.
Process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.

>2. Thread-based Multitasking (Multithreading)

Threads share the same address space.
Thread is lightweight.
Cost of communication between the thread is low.

Note: At least one process is required for each thread.

What is Thread ?

A thread is a lightweight subprocess, a smallest unit of processing. It has a separate path of execution. It shares the memory area of process.
Thread is executed inside the process. There is context-switching between the threads.
There can be multiple processes inside the OS and one process can have multiple threads.

Note: At a time only one thread is executed.

Next---> What is life cycle of a Thread



Wednesday, 14 January 2015

What is Association, Aggregation, Composition, Abstraction, Generalization and Dependency ?

These terms signify the relationships between classes. These are the building blocks of object oriented programming  and very basic stuff. But still for some, these terms look like Latin and Greek. Just wanted to refresh these terms and explain in simpler terms.

Association:

Association is a relationship between two objects. In other words,association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects.

Note: Aggregation is a special form of association.Composition is a special form of aggregation.



For Example:  A Student and a Faculty are having an association.

Aggregation:

Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them.Direction between them specified which object contains the other object. Aggregation is also called a “Has-a”
relationship.

For Example: A class contains students. A student cannot exist without a class There exists composition between class and students.


Composition: 

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.



For Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.


Abstraction:

Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It gives you a blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.

For Example: A wire frame model of a car.

Generalization:

Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behaviour are used from the specialization to the generalized class. At a very broader level you can understand this as inheritance. Why I take the term inheritance is, you can
relate this term very well. Generalization is also called a “Is-a” relationship.

For Example: Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization.


Dependency:

Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.


For Example:  Relationship between shape and circle is dependency.

Monday, 12 January 2015

Mostly Used Unix Commands.

Unix Useful Commands:

This post lists commands, including a syntax and brief description.
Note: commands are  case sensitive means cp or Cp r CP all are different.
For more detail about any command you can  use man command which describe about that command.
$ man command_name
i.e. $ man cp

After type the above command you can see description about cp command.

Command used for Files and Directories:

These commands are used to create directories and handle files.

Command                    Description

cat file_name:              display file contents
cat vishwa.sh :              display contents of vishwa.sh file
 
cd dir_name  :               change directory to dir_name
cd d :                               change to d directory

chgrp  :                         change file group

chmod rwx                       Changing Permissions of file
chmod 777 test.txt           change full permission to text.txt

cp source_file  dest_file   Copy source file into destination
cp test.txt test_data.txt     copy a new file as test_data.txt

file                                    Determine file type
file test.txt                        ascii text type

find                                  Find files
find test.txt                      it print text.txt file if exist otherwise no such file or directory

grep                                 Search files for regular expressions.
grep "txt"                        it will search all file with txt type.(It is used with other commands with                                                 pipleline(|) command to concat. results.
i.e. ls | grep "txt"  It will show all the files of .txt extension on terminal.

head                               Display first few lines of a file
head test.txt                   It will display few top line of file test.txt file.

ls                                   Display information about file type.
ls                                   It will display all the files and directory at the current location.
ls -l                               It will display all files with access permission,owner,date,time etc information

mkdir                           Create a new directory name
mkdir vishwa               will create a file name as vishwa in D directory

more                            Display data in paginated form.
more test.txt               will display data in step by step format

mv                               Move (Rename a file) a oldname to newname.
mv test.txt test_copy.txt   will create a new file with name text_copy.txt

pwd                              Print current working directory.
pwd                             will print the current working directory
pwd                             /home/vishwarup (in my system).

rm                                Remove (Delete) a filename
rm test.txt                    will remove test.txt file
rm -r vishwa                will remove vishwa folder (here -r is used to remove folder).

rmdir                            Remove  an existing directory provided it is empty.
rmdir vishwa               will remove vishwa folder

tail                                Prints last few lines in a file.
trail test.txt                  will print last few line of file.(it is opposite command of head)

touch                           Update access and modification time of a file.
touch test.txt               will update access and modification time of test.txt

Manipulating data:

The contents of files can be compared and altered with the below commands.

awk                                Pattern scanning and processing language

cmp                               Compare the contents of two files
cmm test.txt test data.txt  will compare these two files

comm                  Compare sorted data

cut                     Cut out selected fields of each line of a file

diff                    Differential file comparator

expand                        Expand tabs to spaces

join                    Join files on some common field

perl                                   Data manipulation language

sed                                    Stream text editor

sort                          Sort file data
sort test.txt                       will sort all data of file test.txt

split                           Split file into smaller files

tr                             Translate characters

wc                   Count words, lines, and characters
wc test.txt    will count words,lines and characters

vi   Opens vi text editor
vi test.txt           will open vi editor with name test.txt

vim    Opens vim text editor
vim test.txt            open test.txt file in vim editor

fmt    Simple text formatter

spell            Check text for spelling error


Compressed Files:

Files may be compressed to save space.Compressed files can be created and examined by below commands:

compress                  Compress files

gunzip          Uncompress gzipped files

gzip                 GNU alternative compression method

unzip          List, test and extract compressed files in a ZIP archive

Zcat                 Cat a compressed file

Network Communication:

These following commands are used to send and receive files from a local UNIX hosts to the remote host around the world.

ftp         File transfer program

rcp         Remote file copy

rlogin         Remote login to a UNIX host

rsh        Remote shell

tftp               Trivial file transfer program

telnet       Make terminal connection to another host

ssh       Secure shell terminal or command connection

scp        Secure shell remote file copy

sftp                secure shell file transfer program

Some of these commands may be restricted at your computer for security reasons.

Misc Commands:

Chown        Change owner

date                will display date with day and time

cal        will display calender

echo               to print text on terminal
echo vishwa       will print vishwa on terminal

exit                will close the current working terminal

ps        will display the process Id

kill                to kill any process name with process id

kill process_id                to kill process_id

last                Show last logins of users

logout        log off UNIX

netstat        Show network status

passwd        Change user password

....................................