Hub Of Geekz

  • Home
  • About Me
  • Contact Us
  • Home
  • Languages
    • C++
    • Java
    • Perl
    • Prolog
    • Bootstrap
  • Database
    • SQL
    • PL/SQL
  • Study
    • Java
      • Java Collection
      • Java Concurrency
      • Java Interview Questions
      • Java Networking
    • Number System
  • Kavita
  • Entertainment
    • Hinglish Cafe
    • Videos
    • Jokes
  • Windows Tricks
  • How To
Showing posts with label Thread. Show all posts
Showing posts with label Thread. Show all posts

Thursday, 5 March 2015

Synchronization in Java

 Unknown     07:14     Concurrency, Java, Thread     No comments   

What is thread synchronization?
Suppose we have a multi-threaded application i.e. our application have more than one thread.Since we know multiple threads can share an object.Suppose we have an object which is shared by multiple threads because of this unexpected results can occur unless access to shared object is managed properly.For example:We have two threads which are going to update that shared object what will happen if one thread is updating that object and another thread is in process of updating that thread and another thread is going to read that data.Then what will happen,Which data the third thread will read?
Old data or first thread's data or second thread's data.
What will happen if third thread was supposed to read that old data but has read the new data either of first or second thread.So data is not correct.
The above problem can be solved by giving only one thread access to shared thread on time exclusive basis and at the same time if another thread wants to access that shared object then it has to wait until the thread with that exclusive lock has finished its operation.So this  operation is called as Thread Synchronization.By synchronizing threads in this manner ensures that only one thread is using that shared object and other threads are waiting to access that object.This is called as Mutual Exclusion.
We need to synchronize only mutable data, there is no need to synchronize the immutable data.

How to perform synchronization?
Now we know basics of synchronization.Our next question is how to perform this synchronization in Java.
In Java,There is a concept of monitor.Each object has a monitor and a monitor lock(also known as intrinsic lock). This monitor is used to perform synchronization.Monitor ensures that the monitor lock is held by at most one thread at a time and this ensures mutual exclusion.If a thread want to access a shared object then it has to acquire the lock so that thread will be allowed to access that objects data.Other threads attempting to perform the operation which requires the same lock will be blocked until the first thread releases the lock and after that other thread can acquire the lock to perform operation.
The code which will be executed by the threads will be put in the synchronized block.The code inside the synchronized block is said to be guarded by the monitor lock.So thread has to acquire the lock in order to use that guarded block.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Tuesday, 3 March 2015

Concurrency in Java

 Earthcare Foundation NGO     09:21     Concurrency, Java, Thread     No comments   

Every computer user want to do works in a fast way and they also want to do multiple works at a time. Suppose a user is working on MS Paint and now he can't open anything else. Means when he will finish the paint related work after that he can open other applications.Then it will be very bad for user.So to overcome these types of situations concurrency has introduced.So that user can run multiple applications at a time and the processing of the application increases.Even concurrency can be applied at the process level so that appication can concurrently execute more than one task at a time.
Concurrent programming difficulties:Concurrent programming is not so easy.Suppose you are reading one newspaper,one novel and one maths book and you are reading one book for some seconds say 15 and after that you are reading newspaper for 15 seconds and then you are reading novel for 15 seconds.What are the complexities in this procedure.There are a lot of things you have to do.First you have to switch between these readings and after that you have to remember the page numbers and then you also have to remember the line number so that you can continue.So above is a simple example by which you can understand that concurrent programming is not a simple task.
In concurrent programming there are two basic units of execution:
1)Process
2)Thread
A process has a self contained execution unit.Processes communicate to each other via IPC(Inter process communication).Each process has its own memory space.Most implementations of the Java virtual machine run as a single process. A Java application can create additional processes using a ProcessBuilder object.
A thread is also known as the lightweight process.Thread also provides a execution environment.Each process has atleast one thread.A thread can also create another thread.In java when you run the program a thread is created called main thread which can also create another thread.
We can define and start a thread in two ways:
1)Using runnable interface
2)inheriting Thread class
Click Here to know implementation of thread
Which of two ways is more beneficial.The first way which employe a runnable object is more general because it can subclass any class apart from Thread.The second method is easier to use in simple applications.So Runnable is used for high level applications and is more flexible approach.

Sleep():Thread.sleep causes the current thread to suspend execution for specified time.This method is provided so that other thread of the same process can use the  processor time or any other application can also make use of that time.There are two overloaded methods:
sleep(time in milisecond)
sleep(time in milisecond,time in nanosecond)
However these sleep times are not  guaranteed to be precise because they are facilitated by underlying OS.
Program Code:
package examples;

public class ThreadSleep {

public static void main(String[] args) throws InterruptedException {

for (int i=0;i<10;i++){
//sleep for two seconds
Thread.sleep(2000);
System.out.println(i);
}
}

}
Output:
0
1
2
3
4
5
6
7
8
9
Numbers from 0 to 9 has been printed at a interval of 2 seconds.In program main method throws an InterruptedException.This is an exception that sleep throws when another thread interrupts the current thread while sleep is active.

Interrupts:Interrupts are the indications to the threads to stop doing the thing which they are currrently doing and its upto the programmer how has he programmed the thread to do when an interrupt has generated. But in most scenarios threads are terminated.
 If thread is in any method and and it is interrupted then the best option is that thread should return from that method.We can explain it in example:
public class ThreadSleep {

public static void display() {

for (int i=0;i<10;i++){
//sleep for two seconds
try{
Thread.sleep(2000);
}catch(InterruptedException e){
return ;
}
System.out.println(i);
}
}

}
So in above method if exception comes then it should return from that method.
Now there can be a case,in above example we know that Thread.sleep() method will throw an exception an d then we can know there is interruption but suppose thread is using a method which does not use any other method which wil throw an exception.Then how will that thread will be interrupted.So for this we will use Thread.interrupted() which will return true if there is interrupt so that thread can be interupted.
For example:
public void disp(){
System.out.println("Hi this is abhishek awasthi");
if(Thread.interrupted())
return ;
}
join():Join method allows one thread to wait until other is complete.Suppose there are more than one thread and you want a proper sequence in which the thread should be executed then what can we do.Well we can use this join method.
Suppose there are three threads T1,T2,T3 and we want the sequence to be T1,T2,T3 then we can do one thing  we can call T1.join() and then we can call T2.join.So T1 will be completed first then T2 and then T3.In this way we can preserve the sequence of executing the threads.

So above is basics about concurrency in java.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Runnable in Java

 Earthcare Foundation NGO     09:00     Concurrency, Java, Thread     No comments   

First question is,What is runnable?
So runnable is an interface which is used to provide concurrency to the application by providing the threads to the application.It is the general way of creating threads.

Why should we use runnable interface over Thread class?
If we use Thread class then we have to create our own threads.We will have to manage it on our own.Means a lot of burden will be on the application.
Lets know the execution of runnable interface.So runnable object can be executed by Executor object.So what is this Executor?
An Executor object is used to execute runnable objects.It does this by creating and managing a group of threads in a thread pool.When a Executor begins executing a Runnable,the executor calls the Runnable's run method which is executed in the new thread.
So the next question is how does this Executor manages the threads?
Executor interface has a single method named as execute() which accepts the Runnable as argument.When execute method is called it selects a thread and assigns this thread to the passed Runnable object.If there is no thread available in thread pool then Executor creates the new thread and assigns it to the Runnable object.So this is the main advantage of using Runnable over Thread class.Since Executor can reuse the threads to eliminate the overhead of creating the thread whenever possible.This will optimize the performance of application.
Executor Service can be started by following statement:
ExecutorService service = Executors.newCachedThreadPool();


Program Code:
package examples;

public class ThreadEx  implements Runnable{

String name;
int time;
public ThreadEx(String name,int time){
this.name=name;
this.time=time;
}
@Override
public void run() {

System.out.println("Hi this is thread "+name);
try{
Thread.sleep(time);
}catch(InterruptedException e){
return ;
}
System.out.println("I am last executable line in thread "+name);

}

}

package examples;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadDemo {

public static void main(String[] args) {

ThreadEx t1=new ThreadEx("t1",2000);
ThreadEx t2=new ThreadEx("t2",1000);
ThreadEx t3=new ThreadEx("t3",1500);

System.out.println("Starting Executor");

ExecutorService service=Executors.newCachedThreadPool();
service.execute(t1);
service.execute(t2);
service.execute(t3);

service.shutdown();
System.out.println("Executor Shutdown");
}

}

Output1:
Starting Executor
Hi this is thread t1
Executor Shutdown
Hi this is thread t2
Hi this is thread t3
I am last executable line in thread t2
I am last executable line in thread t3
I am last executable line in thread t1

Output2:
Starting Executor
Executor Shutdown
Hi this is thread t2
Hi this is thread t1
Hi this is thread t3
I am last executable line in thread t2
I am last executable line in thread t3
I am last executable line in thread t1
In output2 main thread terminates before any of the ThreadEx objects outputs their statements and in output1 t1 object has output its statement before main thread terminated.This illustrates the face that we can't predict the order in which the tasks will be executed.It doesn't dependes upon the order in which they have created and started.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Sunday, 1 March 2015

Thread concept in java

 Earthcare Foundation NGO     06:25     Concurrency, Java, Thread     No comments   

A thread is known as a lightweight process. A thread is a basic processing unit to which an operating system can allocate processor time.It is better to use threads, but it doesn't mean that we can create as many as threads and our process will become more efficient. But as we know that threads also consume resources so we should create threads according to the need of application.
Every java program has at least one thread and that thread executes the java program.It is created when the main method of java program is invoked.A java program can have also more than one threads. For example a swing application has at least two threads.

Thread creation:Thread can be created in two ways:
1. Extend the java.lang.Thread class.
2. Implement the java.lang.Runnable interface.

In second method we have to override the run method. Now when the thread is started by calling the start() method run() method will automatically called.Once the run() method returns or throws an exception, the thread dies and will be garbage-collected.
A thread can be in following states during its lifetime:
new,runnable,blocked,waiting,terminated,timed_waiting
The values that represent these states are encapsulated in the java.lang.Thread.State enum. The members of this enum are
NEW, RUNNABLE, BLOCKED, WAITING,TERMINATED and TIMED_WAITING.

package threads;

public class ExtendThread extends Thread {


public static void main(String[] args) {

ExtendThread thread = new ExtendThread();
thread.start();
System.out.println("Hi this is a thread example");

}
}
Above is an example of creating thread using method 1

package threads;

public class ImplementsRunnable implements Runnable {


public void run() {

for(int i=0;i<100;i++){
System.out.println(i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {

e.printStackTrace();
}
}

}

public static void main(String[] args) {

ImplementsRunnable obj = new ImplementsRunnable();
Thread thread = new Thread(obj);
thread.start();

}
}

This is another method which is by implementing runnable method. In this example we have created a class which implements runnable interface,So we have to override run method of thread.In main method we have created an object of this class and passed this object in thread constructor so that a thread will be created for this class.In run method we are just printing numbers from 1 to 99 and we have also used a sleep method of thread which will sleep the thread for specified time.After we have started the thread by calling start() method, run() method of the thread will be automatically called
and executed.

Thread priority:When there are multiple threads in our application, we have to decide the scheduling of those threads. For this we can set the priorities to different threads. We can use the following method:
public final void setPriority(int priority)
Synchronization:Since we know that threads run independently but we may get a situation in which threads have to access the shared data. In this situation what will happen if two threads will access the same data and one thread is reading that data and other thread is modifying that data.
Now in this situation we can't guarantee for the correct data.So for these situations we have synchronization. The shared data can be synchronized so that if one thread is using that data no other thread can access that data until first thread has not completed the task. This synchronization is performed by using monitor lock. When a thread has a lock on some synchronized object and if another thread tries to access that thread then that thread will be blocked till the first thread finish the task using that synchronized object.

Method Synchronization:We can synchronize any method by writing synchronized keyword in method header.


    public synchronized int addition(int a, int b) {

        return a+b;

    }


Block synchronization:Block synchronization can be used to synchronize a block. Suppose an object has to be shared among threads and it is not synchronized and also we don't have access to its code then what will happen? What can we do?We can synchronize it by using block synchronization.
Suppose object1 needs to be synchronized then we can synchronize it by using this
synchronized(object1){
//call the methods of that object
}

So above is all about threads.Kindly comment if you want to know more.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Older Posts Home

Ad


Jobsmag.inIndian Education BlogThingsGuide

Subscribe

Do you want fresh and hot updates about us? Then subscribe to our Feeds.

Total Pageviews

Popular Posts

  • Write a program in PL/SQL to print the factorial of a number.
    In this post I will explain how to get the factorial of any given number. For that first you need to know what is the procedure to find ...
  • To find the GCD of two numbers in PROLOG.
    gcd(X,Y):-X=Y,write('GCD of two numbers is '),write(X); X=0,write('GCD of two numbers is '),write(Y); Y=0,write('G...
  • Write a PL/SQL code to get the Fibonacci Sequence
    First, I will explain what is Fibonacci Sequence and how to get this series. So, Fibonacci Sequence is a series of numbers 0,1,1,2,3,5,8,1...

Label

All Articles Best Resources Blogging Boost Traffic Bootstrap C Plus Plus Collection Comedy Comedy Posts Comedy Videos Concurrency creative commons website Education Employee Entertainment Fibonacci Sequence free images GirlFriend Hinglish Cafe How To Image Websites Inspirational Java Java Interview Questions Java Networking Kavita Sangrah Life Lock Sreen Love Number System Patterns Perl Picture PL/SQL Plastic Engineering Programming Prolog public domain SEO Servlet Short Story Shortcut Keys Social Media Social Services SQL SuVichar Thread Traffic True Events Ultimate Guide Windows Tricks Windows8.1 WordPress

Blog Archive

  • ▼  2020 (43)
    • ▼  September (41)
      • कुल 33 प्रकार के देवी देवता हैँ हिँदू धर्म मे
      • तीन ऋण -
      • चारपीठ
      • चार युगों के नाम
      • चार धाम
      • चार वेद
      • चार आश्रम
      • चार अंतःकरण
      • पञ्च गव्य
      • पञ्च देव
      • पंच तत्त्व
      • छह दर्शन
      • दो पक्षो के नाम
      • सप्त ऋषियों के नाम
      • सप्त पुरी के नाम
      • आठ योग
      • आठ लक्ष्मी
      • नव दुर्गा
      • दस दिशाओ के नाम
      • प्रभु विष्णु के ११ अवतार
      • सनातन संस्कृति के अनुसार बारह महीनों के नाम
      • बारह राशियों के नाम
      • श्री मद्-भगवत गीता"के बारे में महत्वपूर्ण जानकारी
      • धृतराष्ट्र और गांधारी के सौ पुत्र….. कौरव कहलाए ज...
      • पांच पांडवो की माताओ के नाम
      • पांच पांडव के नाम
      • Important Toll Free numbers in India
      • बारह शिव ज्योतिर्लिंग
      • Full form of technical words
      • Full form of abbreviations
      • Trigonometry formulas
      • Chemistry symbols
      • भारतीय संविधान - प्रश्न उत्तर
      • General knowledge question answer
      • Physics formula and relations
      • General knowledge question answer
      • फल/फुल/सब्जी आदि का वैज्ञानिक नाम
      • Chemistry के इम्पोर्टेन्ट सिम्बल्स
      • गणित के महत्वपूर्ण चिन्ह,,
      • पंद्रह तिथियाँ
      • Phrasal Verbs :
    • ►  August (2)
  • ►  2019 (1)
    • ►  July (1)
  • ►  2018 (9)
    • ►  September (7)
    • ►  July (1)
    • ►  May (1)
  • ►  2017 (8)
    • ►  June (3)
    • ►  May (3)
    • ►  March (1)
    • ►  January (1)
  • ►  2016 (2)
    • ►  September (1)
    • ►  January (1)
  • ►  2015 (91)
    • ►  December (1)
    • ►  November (1)
    • ►  October (6)
    • ►  May (10)
    • ►  March (20)
    • ►  February (50)
    • ►  January (3)
  • ►  2014 (339)
    • ►  December (1)
    • ►  October (55)
    • ►  September (58)
    • ►  August (94)
    • ►  July (64)
    • ►  June (67)
  • ►  2013 (34)
    • ►  August (5)
    • ►  April (29)
  • ►  2012 (20)
    • ►  November (1)
    • ►  October (15)
    • ►  September (4)

Author

  • Earthcare Foundation NGO
  • Kavita house
  • Unknown
  • Unknown

Info

Copyright © Hub Of Geekz | Powered by Blogger
Design by Hardeep Asrani | Blogger Theme by NewBloggerThemes.com | Distributed By Gooyaabi Templates