SIDE-BANNERSIDE-BANNER * Oh God! Let there be PEACE. Make them calm, gentle, humble and stable. Make them realize their mistakes. Make them to confess, seek and pray for forgiveness. Let there be forgiveness for true hearts. Show them the right path on which they can walk. Let there be justice, satisfaction and happiness. Let them know that you are the justice and truth. Let them know that the innocent is never punished. Give them the strength, courage and wisdom to quit bad and to achieve good purpose. Let there be leaders who are followed by goodness. Make them competitive to achieve good. Remove their greed, wickedness and bad ambitions. Let them know that your love is infinite. Speak to them in simple ways so they understand. May your heart hear their pure hearts. * Never say die.Live and let live.* Accept Good if not, it Perishes.* What you Sow is what you Reap.* United we Stand divided we Fall.* Where there is a Will there is a Way.* Love is the strongest Power on earth.* When going gets Tough the Tough gets going.* For every problem created there is a perfect Solution.* When your hand starts paining you don't Cut it, Cure it.* A good purpose of life is the persistence to be constructive.* The arch of justice is wide, but it bends towards freedom and justice.* Lion king says he wants all the Power but none of the Responsibilities.* Life is a puzzle which can be solved by Hard work, Character and Discipline.* Money is like Manure, Spread it and it does good.* Pile it up in one place and it Stinks.* When a man wants to be a King he should exactly know the responsibilities of a King.* The only thing necessary for evil to triumph is for good men to do nothing - Edmund Burke.* Face is the reflection of mind.* A purpose of life is a life of purpose.* Beauty lies in the eyes of the beholder.* Necessity is the mother of all inventions. Real friends are those who help us in troubles.* Freedom and Power are lost if it’s miss utilized. Repeating mistakes will lead to sin and blunders.* Quantity is appreciated only when it has Quality.* Everyday is a new day, which brings hope with it.* Ego of superiority is the destruction of individuality.* We cannot learn to swim without going into the water.* Everything happens for good and thus leads to destiny.* Every problem has a perfect solution, we need to find them.* A good purpose of life is the persistence for constructiveness.* It’s hard to create good things where as it’s easy to break them.* Ideas are appreciated and respected only when we express them.* Mistakes do happen by humans, they are forgiven when we pray.* Freedom means giving others the right to achieve good purposes.* We have to put our efforts and leave the rest for destiny to decide.* All big things start with a first step.* First step is sometimes difficult.* Prayers come true when the purpose is good, thus pray for everyone.* Dreams come true when we have faith and pray for good things in life.* We got to have strength, courage and wisdom to achieve good things in life.* Every relationship has a meaning; we have to give them the proper meaning.* The only thing necessary for the triumph of evil is for good men to do nothing.* If wealth is lost, nothing is lost. If health is lost, something is lost. But, if character is lost, everything is lost.* “Stand up, be bold, be strong. Take the whole responsibility on your own shoulders, and know that you are the creator of your own destiny.” - Swami Vivekananda.
HOME-PAGEREALIZATIONQUOTESPUZZLESPRAYERSPERCEPTIONSMUSIC-DOWNLOADSTORIESJOKES
BOOKSBITTER-TRUTHANCIENT-SCRIPTURESBEAUTIFUL-LIFETHOUGHTSFRIENDSHIPPRAYERS-TO-WORSHIPWinning-Publications

QUANTITY is appreciated only when it has QUALITY. Recitation is the mother of Memory. Necessity is the mother of Invention. Knowledge grows when distributed. Enrichment for Information Technology. Persistence to be constructive is the key to success.

Thursday, February 14, 2008

CORE-JAVA (Threads)

*[READ: Why-JAVA] *[Start-Learning-JAVA] *[Why-Java's-Hot] *[Start-Using-LINUX] *[Java-Q-&-A] *[Question] *[Java-SE-6-Doc] *[Struts-Doc] *[Java-Tutorial-Index] *[Java-Certification]
*[Tech.] *[Struts.] *[Servlet.] *[JSP.] *[EJB.] *[JNDI-JMS] *[SQL.] *[JDBC.]
CORE-JAVA: *[OOP] *[CLASS] *[ABSTRACT] *[EXCEPTIONS] *[THREADS] *[UTILS] *[PACKAGES] *[JVM] *[CASTING] *[NETWORKING] *[RMI-XML] * Add to Google


* What is a task’s priority and how is it used in scheduling?
A task’s priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks. The JVM defines a range of ten logical priorities for Java threads, including:
java.lang.Thread.MIN_PRIORITY = 1
java.lang.Thread.NORM_PRIORITY = 5
java.lang.Thread.MAX_PRIORITY = 10
These values 1 to 10 are passed into Thread.setPriority(int) to assign priorities to Java threads. The default priority of a Java thread is NORM_PRIORITY.
In concurrent programming, there are two basic units of execution: processes and threads. When programming with threads we have one thread actually executing at any given moment.
A PROCESS has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, 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. Multiprocess applications are beyond the scope.
Threads are lightweight processes. Both PROCESSES and THREADS provide an execution environment, but creating a new thread requires fewer resources than creating a new process. Threads exist within a process, every process has at least one. Threads share the process's resources, including memory and open files. From the application programmer's point of view, you start with just one thread, called the main thread. This thread has the ability to create additional threads, as we'll.

* What are the disadvantages of using threads?
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Its a rare case scenario. It does not happen all the time.
Happens when two threads are invoked on the same class synchronized method and are both waiting to enter another synchronized method. Both are waiting over other to exit the entered method block. (See Example)
(compile online)

* Can a lock be acquired on a class? (thread)
Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object. To synchronize threads, the Java programming language uses monitors, which are a high-level mechanism for allowing only one thread at a time to execute a region of code protected by the monitor. The behavior of monitors is explained in terms of locks; there is a lock associated with each object.
Thread Locks: A synchronized method automatically performs a lock action when it is invoked; its body is not executed until the lock action has successfully completed. If execution of the method's body is ever completed, either normally or abruptly, an unlock action is automatically performed on that same lock.

* What is the difference between YIELD and SLEEP?
* The Thread.yield() method, c
auses the currently executing thread object to temporarily pause and allow other threads to execute. YIELD will make a thread to pause until an unless there are no more threads waiting in the Ready-to-run state. If there are other threads in the Ready-to-run state, their priorities determine which thread gets to execute. The YIELD() method gives other threads of the same priority a chance to run. If there are no equal priority threads in the "Runnable" state, then the YIELD is ignored and the thread continues its execution.
* The Thread.sleep(long millis) method, causes the thread to pause its execution and transit to the Sleeping state. The thread will sleep for at least the time specified in its argument. SLEEP thread cannot be made to run until and unless the specified time is completed. SLEEP will throw an InterruptedException if interrupted to run before the specified time.
Difference between the methods Thread.sleep() and Object.wait():
The code sleep(1000); puts thread aside for exactly one second. It cannot be interrupted to start before the specified time.
The code wait(1000), causes a wait of up to one second. A thread can stop waiting and start running before the specified time, if it receives the Object.notify() or Object.notifyAll() call. The method wait() is defined in the class Object and the method Thread.sleep() is defined in the class Thread. Object.notify()
Object.wait(long timeout)
A thread may be blocked because:
1) It has been put to sleep for a set amount of time
2) It is suspended with a call to suspend() and will be blocked until a resume() message
3) The thread is suspended by call to wait(), and will become runnable on a notify or notifyAll message.

* What is the purpose of the wait(), notify(), and notifyAll() methods?
IMP: These methods can be invoked only from within a synchronized context (synchronized method or synchronized block), otherwise, the call will result in an IllegalMonitorStateException.
These methods are used on the "shared object" of thread inter-communication that synchronizes on the same object. Object.NOTIFY() method on an object wakes up a single thread. Object.NOTIFYALL() wakes up all the threads. All the awakened threads compete for the resource, but only one thread gets the resource and the others go back to waiting.
Object.wait() method must be enclosed within a try catch block (Checked Exception). The releasing of the lock of the shared object by the thread allows other threads to run and execute synchronized code on the same object after acquiring its lock. The Object.wait() method causes the current thread to wait until another thread notifies it of a changed condition. The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a "shared resource". When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.

* Whats the difference between notify() and notifyAll()?
Object.notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing a "writer" lock on a file might permit all "readers" to resume).

/* Below example shows three threads, manipulating the same stack. All of them are PUSHING elements on the stack. Note: All the threads are using the same Object's
synchronized method, within which the wait() and notify() are called. Runtime exception occurs if not called within a synchronized block. */

public class WaitAndNotify {
(compile online)
-public static void main(String[] args) { StackClass stack = new StackClass(5);
--new StackPusher("One", stack); new StackPusher("Two", stack); new StackPusher("Three", stack);
--try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } /*end main*/ } /*end class*/

class StackPusher extends Thread { StackClass stack;
-StackPusher(String threadName, StackClass stack) {
--super(threadName); this.stack = stack; setDaemon(true); start(); }
---public void run() { while (true) { stack.push(new Integer(3)); } } /*end run*/} /*end thread*/

class StackClass { private Object[] stackArray; private volatile int topOfStack;
-StackClass (int capacity) { stackArray = new Object[capacity]; topOfStack = 0; }
--public synchronized void push(Object element) { // IMPORTANT: synchronized method is a must.
---while (topOfStack <= 4 ) { ---if (topOfStack >=0 && topOfStack <= 4) { stackArray[topOfStack] = element; } ---if (topOfStack >= 4) {
------try { topOfStack=0; wait(); }
------catch (InterruptedException e) { e.printStackTrace(); } }
---topOfStack = topOfStack + 1; notify(); } /*end while*/} /*end push*/} /*end class*/

* When a thread blocks on I/O, what state does it enter?
A thread enters the waiting state when it blocks on I/O.

* What are the high-level thread states?
The high-level thread states are READY, RUNNING, WAITING, and DEAD.
When a thread is created and started, it is in the "Ready state".

* What state is a thread in when it is executing?
An executing thread is in the "running state".

* How can a dead thread be restarted? (THREAD)
A dead thread cannot be restarted.

* What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the DEAD state.

* What invokes a thread's run() method?
After a thread is started, with its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

* What method is invoked to cause an object to begin executing as a separate thread?
The START() method of the Thread class is invoked to cause an object to begin executing as a separate thread.

* What happens when a thread cannot acquire a LOCK on an object?
If a thread attempts to execute a synchronized method or statement and if it's unable to acquire an object's lock, it enters the WAITING state until the lock becomes available.

* How does multi-threading take place on a computer with a single CPU?
The operating system's Task Scheduler/Processor allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression as if tasks are executed sequentially.

* What happens when you invoke a thread's INTERRUPT method while it is sleeping or waiting?
When a task's interrupt() method is executed, the task enters the READY state and will throw an
InterruptedException when it enters the running state. A thread can be awakened abruptly by invoking the interrupt() method on the SLEEPing thread object. Note that this method is not static, thus can be used only when inherited.

* What are three ways in which a thread can enter the WAITING state?
A thread can enter the waiting state by invoking its SLEEP() method.
When blocked by I/O, and by unsuccessfully attempting to acquire an object's LOCK. By invoking an object's WAIT() method.
It can also enter the waiting state by invoking its (deprecated) SUSPEND() method.

* What are the two basic ways in which classes that can be run as threads may be defined?
A thread class may be declared as a subclass of THREAD, or it may implement the RUNNABLE interface. Implementing interface encourages multiple inheritance.


* What method must be implemented by all threads?
All tasks must implement the run() method, whether they are a subclass of THREAD or implement the RUNNABLE interface. (Ex.)
class RunnableThread implements Runnable {
---Thread runner; // instance of Thread
---public RunnableThread() { } // 1st Constructor
---public RunnableThread(String threadName) {
// 2nd Constructor
-----runner = new Thread(this, threadName); // (1) Create a new thread.
-----System.out.println(runner.getName());
-----runner.start(); }
// (2) Start the thread.
---public void run() { System.out.println(Thread.currentThread()); } }
public class RunnableExample {
---public static void main(String[] args) {
-----Thread thread1 = new Thread(new RunnableThread(), "thread1");
-----Thread thread2 = new Thread(new RunnableThread(), "thread2");
-----RunnableThread thread3 = new RunnableThread("thread3");
---//Start the threads
---thread1.start();
---thread2.start();
try { //delay for one second
---Thread.currentThread().sleep(1000); }
---catch (InterruptedException e) { }
---System.out.println(Thread.currentThread()); } }
(compile online)

* What is daemon thread and which method is used to create the daemon thread?
A: Daemon thread is a LOW priority thread which runs intermittently in the BACK-GROUND for the benefit of other threads.
An example of a daemon thread is the garbage collector. setDaemon() method is used to create a daemon thread. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the thread is started. Using setDaemon(true) will stop the thread execution when main() completes. Daemon threads mean that they end when there are no more non-daemon threads running.

* Why do threads block on I/O?
Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed.

* What is the difference between preemptive scheduling and time slicing? (threads)
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 time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

* What are the different identifier states of a Thread?
The different identifiers of a Thread are:
R - RUNNING or runnable thread
S - SUSPENDED thread
CW - CONDITIONAL WAITING - Thread waiting on a condition variable
MW - MONITOR WAITING - Thread waiting on a monitor lock
MS - MONITOR SUSPENDED - Thread suspended waiting on a monitor lock

* Describe synchronization in respect to multi-threading. (synchronize)
A: With respect to multi-threading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared variable while another thread is in the process of using or modifying the same shared variable. This usually leads to significant errors.

* What are synchronized methods and synchronized statements? (synchronize)
A: Synchronized METHODS are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the LOCK for the method's object or class. (Ex.)
--public class SynchronizedCounter {
----private int c = 0;
----public synchronized void increment() { c++; } }
Synchronized STATEMENTS are similar to synchronized methods. But they can be used within non-synchronized methods (Ex:). Synchronized statements must specify the object that provides the intrinsic lock. A synchronized statement can only be executed after a thread has acquired the LOCK for the object or class referenced in the synchronized statement.
public class MsLunch {
--private long c1 = 0; private long c2 = 0;
--private Object lock1 = new Object(); private Object lock2 = new Object();
public void inc1() { --synchronized(lock1) { c1++; }
}
public void inc2() { --synchronized(lock2) { c2++; } } }

* What is an object's LOCK and which object's have locks? (synchronize)
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. Synchronization is built around an internal entity known as the monitor lock. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.


*[Read: How long can we wait?] *[Read: An attempt for definition.]

Read: Peace Home Download Music Prayers Life Is Beautiful
Life is Beautiful.
*Creating successful constructive personality. *Why God Gave Us Friends? *Way to Paradise. *Creating the Beautiful World. *Doing the job of goodness. *Life is Meaningful. *The A to Z for Goodness. *Life is full of Tests. *History Proves That. *Love in different forms. *True to the heart.

No comments:

About Me

My photo
Simple guy who believes in being Competitive rather than being Ambitious. Persistence to be constructive, without frustrations, is a good purpose of life.
.

* * * * * * * * * * * * *

MeetUp Message Board:
Read: Wishes-and-Prayers. *Issue-of-Illegal-Immigration-&-Happy-Kingdom. *The-New-York-Hillary-Rodham-Clinton *Cast-God-Religion! *Barack-Obama-Meetup *Duty- Responsibility-Law-and-Order *John-Edwards-One-America *Good-Wishes-Life-is-Meaningful-&-Beautiful *Dennis-Kucinich-Meetup *Let-there-be-peace! *Bill-Richardson-for-President-2008 *Logic-of-Good-and-Bad-convert-bad-to-good *MORAL-STORY-Elephants-held-by-small-ropes.
* * * * * * * * * * * * *

Realizations.
*Realizations-In-Real-Life-Please-be-gentle-and-humble. *Manoj-D-Kargudri. *Amazing-Constructive-Vibrations. *Astrology. *Creating-Leaders. *How-ideas-are-concluded-and-decisions-are-materialized. *“Relationships-in-Life”-“Partnerships-in-Life”. *The-path-of-victory-the-path-of-life-winning-in-looseing. *An-attempt-for-definition. *Speak-with-a-heart. *These-are-contagious. *Key-to-happy-kingdom. *MIRACLES. *Better-to-create-one! *Cast-God-and-Religion! *Manoj-Kargudri. *Things-become-inevitable! *We-are-all-looking-for! *Phase-of-Life. *Destiny-Karma-and-God. *Struggle-perfection-and-Money. *Independence-and-Freedom. *Relationships-and-Happiness.
* * * * * *

Quotes.
*Love-Compassion-Tolerance-Forgiveness-Courtesy. *Manoj-D-Kargudri. *True-to-Heart-going-back-to-Basics!
* * * * * *

Puzzles-Riddles-Think.
*River-Crossing-Puzzles-Brain-Teasers. *Manoj-Kargudri. *Perpetual-Motion-Gravity-and-Kinetics. *Illusions-Paradoxes-Perpetually-ascending-staircase. *Milk-man-with-no-measureing-jar. *Amazing-Horoscope-Mind-Reader. *Find-the-hidden-images-in-these-STEREOGRAMS. *Are-they-12-or-13? *What-would-U-do? *ABCD-Four-Digit-Number. *10-Digit-Number. *4-QUESTIONS...GOOD-LUCK! *Think-Wise.
* * * * * *

Prayers.
*God-gave-us-everything-we-ever-needed. *Good-Wishes. *Manoj-Kargudri. *Love-Compassion-Tolerance-Forgiveness-Courtesy. *Interview-With-God! *He-is-the-one! *Candle-of-Hope! *Let-there-be-Peace! *Manoj-Kargudri.
* * * * * *

Perceptions.
*Issue-of-Illegal-Immigration. *To-which-religion-does-this-universe-belongs-to? *Law-and-order-helps-to-maintain-justice. *Implementing-regulations-by-justice. *Putting-our-sincere-efforts. *Religion-and-cast. *Impact-of-reservation-based-on-religion-and-cast. *Free-and-Fare-Education-system-Electoral-system.
* * * * * *

Stories.
*The-Monkey’s-Justice-for-two-cats. *The-Blind-Men-And-The-Elephant. *Manoj-Kargudri. *Two-rich-merchants-and-a-thief. *Healing-is-contagious. *Two-saints-in-a-market-place. *A-Terrible-Fight-Between-Two-Wolves. *Hen-that-laid-golden-eggs. *Healing-forgiveness-and-affection. *Elephants-held-by-small-ropes. *Story-of-Punyakoti-the-strength-of-truth. *What-is-the-reason? *Reply-Depends-on-the-Question. *Critical-mass-Experiment. *The-Brahman's-Wife-and-the-Mongoose. *The-Boy-Who-Cried-Wolf. *Difference-between-Heaven-and-Hell! *Freedom-and-Prison! *It's-in-Your-Eyes!
* * * * * *

Jokes.
*Please-listen-to-me. *The-Silent-Treatment! *Surgeon-Vs-Mechanic. *Manoj-Kargudri. *God's-doing-a-lot-better-job-lately.
* * * * * *

The-Bitter-Truth.
*Duty-Responsibility-Law-and-Order. *"Happy-Kingdom"-proudly-proclaimed-as-"Paradise". *Trying-to-learn-something-for-the-first-time. *Time-is-the-only-solution. *For-every-Action-there-is-an-Equal-and-Opposite-Reaction. *Logic-of-Good-and-Bad. *Manoj-Kargudri. *Duties-Responsibilities-verses-Luxuries-and-Pleasures. *Beggars!
* * * * * *

Life-is-Beautiful.
*Creating-successful-constructive-personality. *Why-God-Gave-Us-Friends? *Way-to-Paradise. *Creating-the-Beautiful-World. *Doing-the-job-of-goodness. *Life-is-Meaningful. *Manoj-Kargudri. *The-A-to-Z-for-Goodness. *Life-is-full-of-Tests. *History-Proves-That. *Love-in-different-forms. *True-to-the-heart.
* * * * * *

Prayers-To-Worship.
*Please-do-not-leave-me-ever. *Let’s-make-it-happen. *Faith-in-Patience. *The-only-one-I've-got. *Someone-somewhere. *How-I-Love-You. *Will-You? *Successful-Life. *Manoj-Kargudri. *Please-say-something. *Way-to-Paradise. *My-Everything.
* * * * * *

Friendship.
*Life-Still-Has-A-Meaning. *Heavenly-Garden. *GOD-SPEAK-TO-ME! *Why-God-Made-Friends? *I-asked-the-Lord! *A-Best-Friend! *Why-GOD-Gave-Us-Friends? *Portrait-of-a-Friend. *Friends-till-the-end. *Some-Assorted! *Forever-Friends. *What-is-a-friend!
* * * * * *

Winning-Publications.
*Significance-of-Nava-ratna (Nava-Graha). *Amazing-Constructive-Vibrations. *Manoj-Kargudri. *The-piercing-of-the-ears (karnavedha) . *Nature-Cure. *Steps-to-improve-work-place. *Steps-Involved-In-Relationships. *Some-of-the-aspects-which-materialize-the-relationships.
* * * * * *

Music-Download.
*Bhakti-Songs. *Manoj-Kargudri. *English-Songs. *Gazal-Bhajan-Hindi. *Hindi-Life. *Hindi-Love. *Hindi-Old-Kishore. *Hindi-Old-Mukesh. *Hindi-Old-Songs. *Hindi-Rock. *Hindi-Pops. *Instrumental. *Vocal-Ragas.
* * * * * *

Technology.
*READ: Why-JAVA *Manoj-Kargudri. *Start-Learning-JAVA *Why-Java's-Hot *Start-Using-LINUX *Java-Q-&-A *Question *Java-SE-6-Doc *Struts-Doc *Java-Tutorial-Index *Java-Certification *Tech. *Struts. *Manoj-Kargudri. *Servlet. *JSP. *EJB. *JNDI-JMS *SQL. *JDBC. *CORE-JAVA: *OOP *CLASS. *Manoj-Kargudri. *ABSTRACT *EXCEPTIONS *THREADS *UTILS *PACKAGES *JVM *CASTING *NETWORKING *RMI-XML
* * * * * *

MUSIC-DOWNLOAD.
*Hindi-Vocal-Raga. *Hindi-Remix-Rock. *Hindi-Old-Songs. *Hindi-Mukesh-Mohd-Rafi-Songs. *Hindi-LOVE-Songs. *Hindi-Remix-LIFE. *English-Rock-Songs. *Kannada-Janapada-Geete. *Kannada-Film-Songs. *Kannada-Devotional-Songs. *Instrumental-Music. *Manoj-Kargudri. *Hindi-Pop-Songs. *Hindi-Bhakti-Songs. *Hindi-Kishore-Kumar-SAD. *Hindi-Kishore-Kumar-JOY. *Hindi-R-D-Burman. *Hindi-Gazals. *English-Soft-Songs.
* * * * * *

Add to Google