Wednesday, August 31, 2005

SCJP study notes: Chapter 7 Threads

Originally written by Velmurugan Periasamy. Copyright belongs to him.

Chapter 7 Threads

(Some info is outdated if you are preparing for the SCJP 1.4 exam).

· Java is fundamentally multi-threaded.

· Every thread corresponds to an instance of java.lang.Thread class or a sub-class.

· A thread becomes eligible to run, when its start() method is called. Thread scheduler co-ordinates between the threads and allows them to run.

· When a thread begins execution, the scheduler calls its run method.

Signature of run method – public void run()

· When a thread returns from its run method (or stop method is called – deprecated in 1.2), its dead. It cannot be restarted, but its methods can be called. (it’s just an object no more in a running state)

· If start is called again on a dead thread, IllegalThreadStateException is thrown.

· When a thread is in running state, it may move out of that state for various reasons. When it becomes eligible for execution again, thread scheduler allows it to run.

· There are two ways to implement threads.

1. Extend Thread class

· Create a new class, extending the Thread class.

· Provide a public void run method, otherwise empty run in Thread class will be executed.

· Create an instance of the new class.

· Call start method on the instance (don’t call run – it will be executed on the same thread)

2. Implement Runnable interface

· Create a new class implementing the Runnable interface.

· Provide a public void run method.

· Create an instance of this class.

· Create a Thread, passing the instance as a target – new Thread(object)

· Target should implement Runnable, Thread class implements it, so it can be a target itself.

· Call the start method on the Thread.

· JVM creates one user thread for running a program. This thread is called main thread. The main method of the class is called from the main thread. It dies when the main method ends. If other user threads have been spawned from the main thread, program keeps running even if main thread dies. Basically a program runs until all the user threads (non-daemon threads) are dead.

· A thread can be designated as a daemon thread by calling setDaemon(boolean) method. This method should be called before the thread is started, otherwise IllegalThreadStateException will be thrown.

· A thread spawned by a daemon thread is a daemon thread.

· Threads have priorities. Thread class have constants MAX_PRIORITY (10), MIN_PRIORITY (1), NORM_PRIORITY (5)

· A newly created thread gets its priority from the creating thread. Normally it’ll be NORM_PRIORITY.

· getPriority and setPriority are the methods to deal with priority of threads.

· Java leaves the implementation of thread scheduling to JVM developers. Two types of scheduling can be done.

1. Pre-emptive Scheduling.

Ways for a thread to leave running state -

· It can cease to be ready to execute ( by calling a blocking i/o method)

· It can get pre-empted by a high-priority thread, which becomes ready to execute.

· It can explicitly call a thread-scheduling method such as wait or suspend.

· Solaris JVM’s are pre-emptive.

· Windows JVM’s were pre-emptive until Java 1.0.2

2. Time-sliced or Round Robin Scheduling

· A thread is only allowed to execute for a certain amount of time. After that, it has to contend for the CPU (virtual CPU, JVM) time with other threads.

· This prevents a high-priority thread mono-policing the CPU.

· The drawback with this scheduling is – it creates a non-deterministic system – at any point in time, you cannot tell which thread is running and how long it may continue to run.

· Mactinosh JVM’s

· Windows JVM’s after Java 1.0.2

· Different states of a thread:

1. Yielding

· Yield is a static method. Operates on current thread.

· Moves the thread from running to ready state.

· If there are no threads in ready state, the yielded thread may continue execution, otherwise it may have to compete with the other threads to run.

· Run the threads that are doing time-consuming operations with a low priority and call yield periodically from those threads to avoid those threads locking up the CPU.

2. Sleeping

· Sleep is also a static method.

· Sleeps for a certain amount of time. (passing time without doing anything and w/o using CPU)

· Two overloaded versions – one with milliseconds, one with milliseconds and nanoseconds.

· Throws an InterruptedException.(must be caught)

· After the time expires, the sleeping thread goes to ready state. It may not execute immediately after the time expires. If there are other threads in ready state, it may have to compete with those threads to run. The correct statement is the sleeping thread would execute some time after the specified time period has elapsed.

· If interrupt method is invoked on a sleeping thread, the thread moves to ready state. The next time it begins running, it executes the InterruptedException handler.

3. Suspending

· Suspend and resume are instance methods and are deprecated in 1.2

· A thread that receives a suspend call, goes to suspended state and stays there until it receives a resume call on it.

· A thread can suspend it itself, or another thread can suspend it.

· But, a thread can be resumed only by another thread.

· Calling resume on a thread that is not suspended has no effect.

· Compiler won’t warn you if suspend and resume are successive statements, although the thread may not be able to be restarted.

4. Blocking

· Methods that are performing I/O have to wait for some occurrence in the outside world to happen before they can proceed. This behavior is blocking.

· If a method needs to wait an indeterminable amount of time until some I/O takes place, then the thread should graciously step out of the CPU. All Java I/O methods behave this way.

· A thread can also become blocked, if it failed to acquire the lock of a monitor.

5. Waiting

· wait, notify and notifyAll methods are not called on Thread, they’re called on Object. Because the object is the one which controls the threads in this case. It asks the threads to wait and then notifies when its state changes. It’s called a monitor.

· Wait puts an executing thread into waiting state.(to the monitor’s waiting pool)

· Notify moves one thread in the monitor’s waiting pool to ready state. We cannot control which thread is being notified. notifyAll is recommended.

· NotifyAll moves all threads in the monitor’s waiting pool to ready.

· These methods can only be called from synchronized code, or an IllegalMonitorStateException will be thrown. In other words, only the threads that obtained the object’s lock can call these methods.

Locks, Monitors and Synchronization

· Every object has a lock (for every synchronized code block). At any moment, this lock is controlled by at most one thread.

· A thread that wants to execute an object’s synchronized code must acquire the lock of the object. If it cannot acquire the lock, the thread goes into blocked state and comes to ready only when the object’s lock is available.

· When a thread, which owns a lock, finishes executing the synchronized code, it gives up the lock.

· Monitor (a.k.a Semaphore) is an object that can block and revive threads, an object that controls client threads. Asks the client threads to wait and notifies them when the time is right to continue, based on its state. In strict Java terminology, any object that has some synchronized code is a monitor.

· 2 ways to synchronize:

1. Synchronize the entire method

· Declare the method to be synchronized - very common practice.

· Thread should obtain the object’s lock.

2. Synchronize part of the method

· Have to pass an arbitrary object which lock is to be obtained to execute the synchronized code block (part of a method).

· We can specify “this” in place object, to obtain very brief locking – not very common.

· wait – points to remember

§ calling thread gives up CPU

§ calling thread gives up the lock

§ calling thread goes to monitor’s waiting pool

§ wait also has a version with timeout in milliseconds. Use this if you’re not sure when the current thread will get notified, this avoids the thread being stuck in wait state forever.

· notify – points to remember

§ one thread gets moved out of monitor’s waiting pool to ready state

§ notifyAll moves all the threads to ready state

§ Thread gets to execute must re-acquire the lock of the monitor before it can proceed.

· Note the differences between blocked and waiting.



Thread is waiting to get a lock on the monitor.

(or waiting for a blocking i/o method)

Thread has been asked to wait. (by means of wait method)

Caused by the thread tried to execute some synchronized code. (or a blocking i/o method)

The thread already acquired the lock and executed some synchronized code before coming across a wait call.

Can move to ready only when the lock is available. ( or the i/o operation is complete)

Can move to ready only when it gets notified (by means of notify or notifyAll)

· Points for complex models:

1. Always check monitor’s state in a while loop, rather than in an if statement.

2. Always call notifyAll, instead of notify.

· Class locks control the static methods.

· wait and sleep must be enclosed in a try/catch for InterruptedException.

· A single thread can obtain multiple locks on multiple objects (or on the same object)

· A thread owning the lock of an object can call other synchronous methods on the same object. (this is another lock) Other threads can’t do that. They should wait to get the lock.

· Non-synchronous methods can be called at any time by any thread.

· Synchronous methods are re-entrant. So they can be called recursively.

· Synchronized methods can be overrided to be non-synchronous. synchronized behavior affects only the original class.

· Locks on inner/outer objects are independent. Getting a lock on outer object doesn’t mean getting the lock on an inner object as well, that lock should be obtained separately.

· wait and notify should be called from synchronized code. This ensures that while calling these methods the thread always has the lock on the object. If you have wait/notify in non-synchronized code compiler won’t catch this. At runtime, if the thread doesn’t have the lock while calling these methods, an IllegalMonitorStateException is thrown.

· Deadlocks can occur easily. e.g, Thread A locked Object A and waiting to get a lock on Object B, but Thread B locked Object B and waiting to get a lock on Object A. They’ll be in this state forever.

· It’s the programmer’s responsibility to avoid the deadlock. Always get the locks in the same order.

· While ‘suspended’, the thread keeps the locks it obtained – so suspend is deprecated in 1.2

· Use of stop is also deprecated, instead use a flag in run method. Compiler won’t warn you, if you have statements after a call to stop, even though they are not reachable.


Blogger jaganrb said...

nice explanation........

6:16 AM  
Blogger sarah said...

This comment has been removed by the author.

7:48 AM  
Blogger sarah said...

Thanks for all the information ,it was very helpful i really like that you are providing information on core and advance java ,being enrolled in
advance and core java i was looking for such information on advance and core java and your information helped me a lot. I really like that you are providing such information. Thanks

7:50 AM  
Blogger peterson said...

Your technical information related with java programming is very useful and interesting. Also share updated details about java in your website. Thanks for sharing this article.
Java training institute in chennai

2:31 AM  
Blogger jack wilson said...

This information you provided in the blog that was really unique I love it!!, Thanks for sharing such a great blog..Keep posting..

J2EE Training in Chennai

11:38 PM  
Blogger vignesh m said...

Hi,i hope to really understand this information.Sharing for useful information...Thanks for that nice blogs!!!hadoop training in chennai....

8:10 PM  
Blogger Ravi Raj said...

Thanks to Share the LoadRunner Material for Freshers,Link as,
LoadRunnerTraining in Chennai

3:05 AM  
Blogger Rajesh Ravi said...

Thanks Good Information for QTP Freshers
Refer thr link,
QTP Training In Chennai


10:49 PM  
Blogger Mani said...

We are the best providers of SharePoint Training in Chennai with experts. Our training program is very much mixed both practical and interview point of questions.


11:43 PM  
Blogger Ganesh M said...

Our Android Training in Chennai aims to teach beginners and employees.Android is the fastest growing smart phone OS in the world today..To know more,follow the below link
Best android training institute in chennai

12:35 AM  
Blogger Ganesh M said...

Our Android Training in Chennai aims to teach beginners and employees.Android is the fastest growing smart phone OS in the world today..To know more,follow the below link
Best android training in chennai

2:11 AM  
Blogger Ravi Raj said...

This page is dedicated for our Besant Technologies Reviews by our students. Please give your reviews here,

Besant Technologies Complaints

11:08 PM  
Blogger Rajesh Ravi said...

This page is dedicated for our Besant Technologies Reviews by our students. Please give your reviews here,

Besant Technologies Reviews

3:27 AM  
Blogger hari m said...

This comment has been removed by the author.

2:03 AM  
Blogger hari m said...

This page is dedicated for our Besant Technologies Reviews and Testimonials by our students. Please give your reviews here,
Besant Tech Review

2:04 AM  
Blogger Success Best said...

Good Collection ...........

Oracle DBA Training in Chennai

3:51 AM  
Blogger Jesica Paul said...

Nice information about the load testing!!! I prefer Loadrunner automation testing tool to validate the performance of software application/system under actual load. Loadrunner training institute in Chennai

11:15 PM  
Blogger Abirami R said...

Java new concepts are really interesting to study.and understand the concept very clearely..
Software Testing Training in Chennai

6:12 AM  
Blogger rebeka christy said...

Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog. Recently I did Software Testing Training in Chennai at a reputed training institutes. This is really useful for me to make a bright future in IT field.

12:25 AM  
Blogger Jamuna Pandy said...

Oracle is a relational database management system produced by oracle corporation. Nowadays most of the multinational companies used this oracle database for storing and managing their data's and programs. So learning Oracle Training in Chennai is one of the best idea to make a bright career.

12:24 AM  
Blogger jack wilson said...

Excellent information. HTML5 is a markup language used for designing responsive website and it is also used for structuring and presenting the website content.
HTML5 Training | PHP Course in Chennai

11:06 PM  
Blogger Jamuna Pandy said...

Nice information. Android is one of the most popular mobile operating system developed by Google. Learning Android Course in Chennai is useful to make a wonderful future in mobile application development field.

12:18 AM  
Blogger savitha singh said...

Nice information. Salesforce is a most powerful CRM tool used for manage all customers including potential customers. Salesforce Training in Chennai offering this course with experienced professionals.

11:15 PM  
Blogger Martina Christy said...

Really nice post. Unix is a multiuser and multi tasking operating system at the same time. Unix Training Chennai offering real time Unix course at reasonable cost.

11:59 PM  
Blogger hari said...

Nice article i was really impressed by seeing this article, it was very interesting and it is
very useful for Learners..
SharePoint Training Institute in Chennai | SharePoint Training

8:47 PM  
Blogger murali karthik said...

Really nice post. SEO is one of the digital marketing techniques used for improve the website ranking in search engine result page. To know more details please call 9003623340.
SEO Training in Chennai

12:40 AM  
Blogger Badrul Jaman said...

Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing....
iOS Training in Chennai | Informatica Training in Chennai

5:30 AM  
Blogger joshsonpeter said...

Hi, You sharing for this article effective information..Thank you so much..

Informatica Training in Chenna

3:17 AM  
Blogger Andrew Son said...

There are lots of information about latest technology and how to get trained in them, like Hadoop Training Chennai have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies(Hadoop Training in Chennai). By the way you are running a great blog. Thanks for sharing this (Salesforce Training institutes in Chennai).

11:42 PM  
Blogger Roshini RS said...

This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.
Informatica training in chennai|SAP training in chennai|Informatica course in Chennai

12:27 AM  
Blogger Rahul said...

Hello Admin, thank you for the informative post. At Fita academy, we provide the best IT trainings for various courses. You can check our Fita Chennai review page to know more about our quality and standards.

11:04 PM  
Blogger Harshita said...

Wow, brilliant article on dot net training in Chennai that I was searching for. Helps us a lot in referring at my dot net training institutes in Chennai. Thanks a lot. Keep writing more on dot net training Chennai, would love to follow your posts and refer to others in dot net training institute in Chennai.

4:47 AM  
Blogger Srishthi B said...

That is a brilliant article on dot net training in Chennai that I was searching for. Helps us a lot in referring at our dot net training institute in Chennai. Thanks a lot. Keep writing more on dot net course in Chennai, would love to follow your posts and refer to others in dot net training institutes in Chennai.

5:10 AM  
Blogger Stephen said...

Testing is the only way to deliver reliable products in the Information Technology market(Software testing training in chennai). Articles like this are vital in improvising one's ability as a software testing professional(Software testing course chennai). Thank you so much for sharing this information in here(Software testing training chennai). Keep blogging.

10:19 PM  
Blogger caroline jesi said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…
ccna course in Chennai|ccna training in Chennai|ccna training institute in Chennai

1:55 AM  
Blogger Anna said...

Great and Useful Article.

Online Java Training

Online Java Training from India

Online Java Training

Online Java Training From India

Java Training Institutes in Chennai

Java Training in Chennai

3:51 AM  
Blogger siddu said...

Good article.Thank you for sharing helpful information.

java online training
advanced java online training
core java online training

3:28 AM  
Blogger Abina Ragav said...

Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us.
... sharepoint Training in chennai

10:39 PM  
Blogger Abina Ragav said...

We provides focus and real time training session, which equipped you with skill to get best career option in the industry. We offered training and certification basic to advance level in Software testing training in Chennai.

5:11 AM  
Blogger Abina Ragav said...

This comment has been removed by the author.

5:11 AM  
Blogger Abina Ragav said...

Thanks for sharing such a great information..Its really nice and informative.
android training in Chennai

5:13 AM  
Blogger Abina Ragav said...

Thanks for sharing this information, it helped me a lot in finding valuable resources for my career
android training in Chennai

5:13 AM  
Blogger Gopi Perumal said...

Cool One Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.

CCNA Training in Chennai | CCNA Training Institute in Chennai | Best CCNA Training in Chennai

5:24 AM  
Blogger Nicky Paul said...

All things considered, there you have it: a few WordPress talk modules to look over. They all convey something somewhat distinctive to the table yet what they share is a goal to make collaborating with and changing over clients only a tiny bit less demanding.
Wp Chat

3:20 AM  
Blogger Rose Angel said...

Thanks a lot for letting me a chance to visit your any pointers. Your article about web design is really impressed me very much.telephone apps

11:15 PM  
Blogger Chinni Bocha said...

Java proramming will be interested..
SEO training in hyderabad by experts in digital markeing And by prosessional experts in seo.All the training by placement and also guide by the professionals.SEO training in hyderabad

5:32 AM  
Blogger Nikshitha S said...

Excellant post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
cloud computing training in chennai | cloud computing courses in chennai

4:28 AM  
Blogger Venu Venu said...

Understanding Products and services of a Dentist
salesforce training in hyderabad

10:43 PM  
Blogger Venky Praise said...

Freshers jobs way provide freshers jobs ,walkins,direct recruitment,openings for freshers and experienced and recruiting experienced and freshers Walkins

9:49 PM  
Blogger Chinni Bocha said...

Excellent posts about java..
sap fiori training in hyderabad

3:41 AM  
Blogger Chinni Bocha said...

Thanku for sharing this excelent posts..

SAP Hana online training in hyderabad

5:53 AM  
Blogger prema said...

useful information

Online recruitment for bank jobs and government jobs and you can get Notification and application to apply

online for bank jobs and govt jobs

3:59 AM  
Blogger Balusomu said...

Recruitment voice contains Daily GK Updates, Bank Recruitment, Government jobs, Bank jobs, Interview Tips, Banking News, GK Updates <a href="

3:53 AM  
Blogger Balusomu said...

Recruitment voice contains Daily GK Updates, Bank Recruitment, Government jobs, Bank jobs, Interview Tips, Banking News, GK Updates bank recruitment

3:56 AM  
Blogger Balusomu said...

Useful Information:
Telugu Cinema Contains Telugu Cinema News, Latest Movie Reviews, Actor, Actress, Movie Galleries And Many More Telugu Cinema

5:49 AM  
Blogger prema said...

Useful information:
General Awareness and Current Affairs with Latest Current Affairs Quiz, GK Updates, General Knowledge Last 6 Months Current Affairs, Placement Papers, Model Papers, Interview Questions @

5:48 AM  
Blogger Nikshitha S said...

Thanks for sharing this informative content that guided me to know the details about the training offered in different technology.
digital marketing course in chennai | digital marketing training

5:11 AM  
Blogger Bhavya Kumar said...

Thanks for the great information in your blog Selenium Training in Chennai

12:50 AM  

Post a Comment

<< Home