Showing posts with label java scjp. Show all posts
Showing posts with label java scjp. Show all posts

Saturday, February 26, 2011

Some Last Words Before you take the SCJP Exam

Thank you for coming this far in the SCJP exam series in my blog. If you have read through and understood the articles in the SCJP exam series, you are now well equipped to crack the SCJP exam. Let me sign-off on this SCJP exam series with a few last words.

So, as usual, lets get started!!!

What This Series Is Not

This series of blog articles is not a beginners guide or a definitive guide to the Java programming language. The articles are written under the assumption that you are someone who knows a little bit of Java and are someone who aims at becoming SCJP certified. This is not the Java Complete reference and there are many advanced topics like RMI (Remote Method Invocation), JDBC (Database Connectivity) etc that we havent covered because, they arent on the exam.

Some Tips

Once you have completed reading all the chapters in this SCJP series, I suggest you do the following:
a. Re-visit all the quick review chapters and go through all the important points about the topics we have covered
b. Re-read all the Exam Tips that are present as Quotes in each chapter and remember them
c. Have someone quiz you with random questions from the self-test chapters
d. Re-visit the self-test chapters and try to answer all the questions (Without checking the answers) (I know you are mumbling Of Course pal, I know that. But still, it is my duty isnt it?)
e. Write java code and I mean lots of it. Coding is the best way to learn the language and nothing can beat it.

The Last Exam Tip:

It is a good practice to review all your answers once you are done answering the questions. It is also important that, you do not change your answers during the review, unless you know that your answer is wrong for sure. Only change an answer when you feel you may have misread or misinterpreted the question the first time. Nervousness may make you second-guess every answer and talk yourself out of a correct one.

Tips on Cracking the Exam

There are 72 questions on the 310-065 (SCJP Java 6) exam. You will need to get at least 47 of them correct to pass—around 65%. You are given over three hours to complete the exam. This information is subject to change. Always check with the Sun official website before taking the exam, at www.suned.sun.com.

Some More Tips:

a. You can answer questions in any order. So if you feel you arent able to answer a question, don't waste too much time on that question, just move on to the next one and you can come back and answer this bad boy later
b. Be careful & cautious on the code examples. Check for syntax errors first: count curly braces, semicolons, and parenthesis and then make sure there are as many left ones as right ones. Look for capitalization errors and other such syntax problems before trying to figure out what the code does.
c. The code may look almost fine and you may be tempted to choose an answer as the possible output, but the code might be missing a closing paranthesis which means it wouldn't compile and you would miss a easy no-brainer in your hurry to answer the question

Well, thank you again for being a patron of my articles and I sincerely hope they were useful and you pass the SCJP exam with flying colors.

All the very best.

Previous Chapter: Other Topics of Importance

Next Chapter: None. This is the last chapter in the SCJP Series. You can go to the first article of this series, if you want by "clicking here"

Friday, February 25, 2011

Chapter 61: Thread Interactions

The last thing we need to look at in our series of chapters on threads, is how threads can interact with one another to communicate about, among other things, their locking status. The Object class has three methods, wait(), notify(), and notifyAll() that help threads communicate about the status of an event that the threads care about.


This is exactly what we are going to see in this chapter.


So, lets get started!!!


Using Wait and Notify


For example, if one thread is a repair-car repair-car thread and one thread is a accept-car-for-service thread, the accept-car-for-service thread has to keep checking to see if there’s any car to accept for service. Using the wait and notify mechanism, the accept-car-for-service thread could check for cars, and if it doesn’t find any it can say, “Hey, I’m not going to waste my time checking for a car every few minutes. I’m going to go hang out, and when a customer drives in with a car for service, have him notify me so I can go back to runnable and do some work.” In other words, using wait() and notify() lets one thread put itself into a “waiting room” until some other thread notifies it that there’s a reason to come back out.


One key point to remember for the exam about wait/notify is this:


wait(), notify(), and notifyAll() must be called from within a synchronized context! A thread can’t invoke a wait or notify method on an object unless it owns that object’s lock.


Here we’ll present an example of two threads that depend on each other to proceed with their execution, and we’ll show how to use wait() and notify() to make them interact safely and at the proper moment.


Think of a computer-controlled Mechanic that repairs cars and the user comes to the garage to drop of his car to repair. The current version of the application has one thread, which loops, first getting the car from the user and then giving it to the mechanic for repair:


public void run(){

while(true){

// Get Car from user

// Analyse and identify faulty parts

// Fix em...

// Send user home happy...

}

}


This design is not optimal because the user can’t do anything while the mechanic is busy and while there are other parts to fix. We need to improve the situation.


A simple solution is to separate the processes into two different threads, one of them interacting with the user and another fixing the car. The user thread sends the instructions to the fixing thread and then goes back to interacting with the user immediately. The fixing thread receives the instructions from the user thread and starts directing the mechanic immediately. Both threads use a common object to communicate, which holds the current car being processed.
The following pseudocode shows this design:


public void keepUserEngagedLoop(){

while(true){

// Get car from user

// Pass car repair instructions to fixing thread

}

}


public void fixingLoop(){

while(true){

// Get car into garage

// start fixing it

}

}


The problem now is to get the fixing thread to process the car as soon as it is available. Also, the user thread should not disturb the car until it is sent to the garage. The solution is to use wait() and notify(), and also to synchronize some of the code.


The methods wait() and notify(), remember, are instance methods of Object. In the same way that every object has a lock, every object can have a list of threads that are waiting for a notification from the object. A thread gets on this waiting list by executing the wait() method of the target object. From that moment, it doesn’t execute any further instructions until the notify() method of the target object is called. If many threads are waiting on the same object, only one will be chosen (in no guaranteed order) to proceed with its execution. If there are no threads waiting, then no particular action is taken. Let’s take a look at some real code that shows one object waiting for another object to notify it:


1. class FirstThread {

2. public static void main(String [] args) {

3. SecondThread b = new SecondThread();

4. b.start();

5.

6. synchronized(b) {

7. try {

8. System.out.println("Waiting for b to complete...");

9. b.wait();

10. } catch (InterruptedException e) {}

11. System.out.println("Value is: " + b.value);

12. }

13. }

14. }

15.

16. class SecondThread extends Thread {

17. int value;

18.

19. public void run() {

20. synchronized(this) {

21. for(int i=0;i<10;i++) {

22. value += i;

23. }

24. notify();

25. }

26. }

27. }



This program contains two objects with threads: FirstThread contains the main thread and SecondThread has a thread that calculates the sum of all numbers from 0 through 9. As soon as line 4 calls the start() method, FirstThread will continue with the next line of code in its own class, which means it could get to line 11 before SecondThread has finished the calculation. To prevent this, we use the wait() method in line 9.


Notice in line 6 the code synchronizes itself with the object b, this is because in order to call wait() on the object, FirstThread must own a lock on b. For a thread to call wait() or notify(), the thread has to be the owner of the lock for that object. When the thread waits, it temporarily releases the lock for other threads to use, but it will need it again to continue execution. It’s common to find code like this:


synchronized(someObject) { // this has the lock on someObject

try {

someObject.wait();

// the thread releases the lock and waits

// To continue, the thread needs the lock,

// so it may be blocked until it gets it.

} catch(InterruptedException e){}

}



The preceding code waits until notify() is called on someObject.

synchronized(this) { notify(); }



This code notifies a single thread currently waiting on the this object. The lock can be acquired much earlier in the code, such as in the calling method. Note that if the thread calling wait() does not own the lock, it will throw an IllegalMonitorStateException. This exception is not a checked exception, so you don’t have to catch it explicitly. You should always be clear whether a thread has the lock of an object in any given block of code.

Notice in lines 7–10 there is a try/catch block around the wait() method. A waiting thread can be interrupted in the same way as a sleeping thread, so you have to take care of the exception:


try {

wait();

} catch(InterruptedException e) {

// Do something about it

}


In the car garage example, the way to use these methods is to have the fixing thread wait on the car to be available and the user thread to notify after it has finished giving the car. The fixing steps may comprise global steps, such as moving the car to the garage area, and a number of substeps, such as checking the engine, transmission. As an example they could be


int NumberOfCylindersInEngine;

int NumberOfGearsInTransmission;

Engine engineMake;

float[] tires;

etc..


It is important that the user thread does not modify the car details while the fixing thread is using them, so this reading and writing should be synchronized.


The resulting code would look like this:

class User extends Thread {

public void run(){

while(true){

// Get car from user

synchronized(this){

// identify details to fix the car

notify();

}

}

}

}


class Mechanic extends Thread {

User User; // assume this gets initialized

public void run(){

while(true){

synchronized(User){

try {

User.wait();

} catch(InterruptedException ie) {}

// Send Mechanic steps to fixing

}

}

}

}


The Mechanic thread, once started, will immediately go into the waiting state and will wait patiently until the User sends the first notification. At that point it is the User thread that owns the lock for the object, so the fixing thread gets stuck for a while. It’s only after the User thread abandons the synchronized block that the fixing thread can really start processing the Mechanic steps.


While one car is being processed by the mechanic, the user may interact with the system and specify another car to be serviced. When the user is finished with the car and it is time to repair it, the User thread attempts to enter the synchronized block, maybe blocking until the Mechanic thread has finished with the previous Mechanic steps. When the Mechanic thread has finished, it repeats the loop, going again to the waiting state (and therefore releasing the lock). Only then can the User thread enter the synchronized block and overwrite the Mechanic steps with the new ones.


Having two threads is definitely an improvement over having one, although in this implementation there is still a possibility of making the user wait. A further improvement would be to have many cars in a queue, thereby reducing the possibility of requiring the user to wait for the mechanic.


There is also a second form of wait() that accepts a number of milliseconds as a maximum time to wait. If the thread is not interrupted, it will continue normally whenever it is notified or the specified timeout has elapsed. This normal continuation consists of getting out of the waiting state, but to continue execution it will have to get the lock for the object:


synchronized(a){ // The thread gets the lock on 'a'

a.wait(5000); // Thread releases the lock and waits for notify

// only for a maximum of five seconds, then goes back to Runnable

// The thread reacquires the lock

// More code here

}


Exam Tip:
When the wait() method is invoked on an object, the thread executing that code gives up its lock on the object immediately. However, when notify() is called, that doesn’t mean the thread gives up its lock at that moment. If the thread is still completing synchronized code, the lock is not released until the thread moves out of synchronized code. So just because notify() is called doesn’t mean the lock becomes available at that moment
Using notifyAll( )

In most scenarios, it’s preferable to notify all of the threads that are waiting on a particular object. If so, you can use notifyAll() on the object to let all the threads come out of the waiting area and back to runnable. This is especially important if you have several threads waiting on one object, but for different reasons, and you want to be sure that the right thread (along with all of the others) gets notified.


notifyAll(); // Will notify all waiting threads


All of the threads will be notified and start competing to get the lock. As the lock is used and released by each thread, all of them will get into action without a need for further notification.


As we said earlier, an object can have many threads waiting on it, and using notify() will affect only one of them. Which one, exactly, is not specified and depends on the JVM implementation, so you should never rely on a particular thread being notified in preference to other threads.


In cases in which there might be a lot more waiting, the best way to do this is by using notifyAll(). Let’s take a look at this in some code. In this example, there is one class that figures out a stocks current price and many stock traders that are waiting to receive the current value. At any given moment many traders may be waiting.


1. class Trader extends Thread {

2. StockPriceAnalyzer c;

3.

4. public Trader(StockPriceAnalyzer calc) {

5. c = calc;

6. }

7.

8. public void run() {

9. synchronized(c) {

10. try {

11. System.out.println("Waiting for calculation...");

12. c.wait();

13. } catch (InterruptedException e) {}

14. System.out.println("Value is: " + c.value);

15. }

16. }

17.

18. public static void main(String [] args) {

19. StockPriceAnalyzer StockPriceAnalyzer = new StockPriceAnalyzer();

20. new Trader(StockPriceAnalyzer).start();

21. new Trader(StockPriceAnalyzer).start();

22. new Trader(StockPriceAnalyzer).start();

23. StockPriceAnalyzer.start();

24. }

25. }

26.

27. class StockPriceAnalyzer extends Thread {

28. int value;

29.

30. public void run() {

31. synchronized(this) {

32. for(int i=0;i<10;i++) {

33. value += i;

34. }

35. notifyAll();

36. }

37. }

38. }


The program starts three threads that are all waiting to receive the finished calculation (lines 18–24), and then starts the StockPriceAnalyzer with its calculation. Note that if the run() method at line 30 used notify() instead of notifyAll(), only one Trader would be notified instead of all the Traders.


Apologies for the crappy code inside the stock market prize analyzer class. I cant probably put code that calculates the current price of any share in such a small place. So I just put in some code that does addition in a loop. As long as you understand the concept and not curse me for the example I am good!!!


Using wait( ) in a Loop


Actually both of the previous examples (Mechanic/User and Trader/StockPriceAnalyzer) had a common problem. In each one, there was at least one thread calling wait(), and another thread calling notify() or notifyAll(). This works well enough as long as the waiting threads have actually started waiting before the other thread executes the notify() or notifyAll(). But what happens if, for example, the StockPriceAnalyzer runs first and calls notify() before the Traders have started waiting? This could happen, since we can’t guarantee what order the different parts of the thread will execute in. Unfortunately, when the Traders run, they just start waiting right away. They don’t do anything to see if the event they’re waiting for has already happened. So if the StockPriceAnalyzer has already called notifyAll(), it’s not going to call notifyAll() again—and the waiting Traders will keep waiting forever. This is probably not what the programmer wanted to happen. Almost always, when you want to wait for something, you also need to be able to check if it has already happened. Generally the best way to solve this is to put in some sort of loop that checks on some sort of conditional expressions, and only waits if the thing you’re waiting for has not yet happened. Here’s a modified, safer version of the earlier Car & Mechanic example:


class User extends Thread {

Mechanic Mechanic; // assume this gets initialized

public void run() {

while (true) {

Car car = getCarFromUser();

MechanicInstructions job = processCarForInstructions(shape);

Mechanic.addCarForRepair(job);

}

}

}



The User will still keep on looping forever, getting more cars from users, calculating new instructions for those cars, and sending them to the Mechanic. But now the logic for notify() has been moved into the addCarForRepair() method in the Mechanic class:


class Mechanic extends Thread {

List jobs = new ArrayList();

public void addCarForRepair(MechanicInstructions job) {

synchronized (jobs) {

jobs.add(job);

jobs.notify();

}

}

public void run() {

while (true) {

synchronized (jobs) {

// wait until at least one car is available

while (jobs.isEmpty()) {

try {

jobs.wait();

} catch (InterruptedException ie) { }

}

// If we get here, we know that jobs is not empty

MechanicInstructions instructions = jobs.remove(0);

// Send Mechanic steps to garage

}

}

}

}


A Mechanic keeps a list of the jobs it’s scheduled to do. Whenever an User adds a new job to the list, it calls the addCarForRepair() method and adds the new job to the list. Meanwhile the run() method just keeps looping, looking for any jobs on the list. If there are no jobs, it will start waiting. If it’s notified, it will stop waiting and then recheck the loop condition: is the list still empty? In practice this double-check is probably not necessary, as the only time a notify() is ever sent is when a new job has been added to the list. However, it’s a good idea to require the thread to recheck the isEmpty() condition whenever it’s been woken up, because it’s possible that a thread has accidentally sent an extra notify() that was not intended.


There’s also a possible situation called spontaneous wakeup that may exist in some situations; a thread may wake up even though no code has called notify() or notifyAll().What this means is, when your thread wakes up from a wait(), you don’t know for sure why it was woken up. By putting the wait() method in a while loop and re-checking the condition that represents what we were waiting for, we ensure that whatever the reason we woke up, we will re-enter the wait() if and only if the thing we were waiting for has not happened yet. In the Mechanic class, the thing we were waiting for is for the jobs list to not be empty. If it’s empty, we wait, and if it’s not, we don’t.


Note also that both the run() method and the addCarForRepair() method synchronize on the same object, the jobs list. This is for two reasons. One is because we’re calling wait() and notify() on this instance, so we need to synchronize in order to avoid an IllegalThreadState exception. The other reason is, the data in the jobs list is changeable data stored in a field that is accessed by two different threads. We need to synchronize in order to access that changeable data safely. Fortunately, the same synchronized blocks that allow us to wait() and notify() also provide the required thread safety for our other access to changeable data. In fact this is a main reason why synchronization is required to use wait() and notify() in the first place, you almost always need to share some mutable data between threads at the same time, and that means you need synchronization. Notice that the synchronized block in addCarForRepair() is big enough to also include the call to jobs.add(job,)which modifies shared data. And the synchronized block in run() is large enough to include the whole while loop—which includes the call to jobs.isEmpty(), which accesses shared data.


The moral of the story here is (again value education stuff) that when you use wait() and notify() or notifyAll(), you should almost always also have a while loop around the wait() that checks a condition and forces continued waiting until the condition is met. And you should also make use of the required synchronization for the wait() and notify() calls, to also protect whatever other data you’re sharing between threads. If you see code which fails to do this, there’s usually something wrong with the code, even if you have a hard time seeing what exactly the problem is.


Exam Tip:
The methods wait() , notify(), and notifyAll() are methods of only java.lang.Object, not of java.lang.Thread or java.lang.Runnable. Be sure you know which methods are defined in Thread, which in Object, and which in Runnable (just run(), so that’s an easy one). Of the key methods in Thread, be sure you know which are static—sleep() and yield(), and which are not static—join() and start()

Key Thread Methods

To wrap up this chapter, we will take a look at the important thread methods and then we will call it a day!!!


Methods in the Object Class:
a. wait()

b. notify()

c. notifyAll()



Methods in the Thread Class:
a. start()

b. yield()

c. sleep()

d. join



Methods in the Runnable Interface:
a. run()


That's it folks. We are done with Threads!!! Ugh, that was pretty long and hard. Wasn't it? :-)

Previous Chapter: Chapter 60 - Synchronization

Next Chapter: Quick Review - Threads

Chapter 60: Synchronization

We have been using the term synchronizing multiple times over the course of the previous chapters. We have never cared to stop and explain what the term synchronizing or synchronization means. Well, here we are. This full chapter is dedicated to synchronization and how to synchronize our code.

So, lets get started!!!

Why do we need Synchronization?

Threads are a powerful concept that we explained in the previous few chapters. Just as in the case of any programming scenario, the code works on a set of data and processes it. Lets imagine a scenario:

Assume that I have borrowed Rs. 10000/- from you and another Rs. 10000/- from an anonymous Mr. X last month. Now, both of you are chasing me for the money and I give you cheques worth the money I owe you guys, each worth Rs. 10000/- so, now I have given cheques worth Rs. 20000/- for payment. Unfortunately for you both, my account has a balance of only Rs. 12000/- and fortunately for me the banking application of my bank does not care about synchronization. So here is what will happen in a hypothetical situation wherein both the cheques are going to be submitted for payment at the same time.

Bank A (Your bank) and Bank B (Mr. X’s bank) have both submitted the cheques for payment to my bank today morning at two different branches.

A teller is processing your cheque at branch 1 and another teller is processing Mr. X’s cheque at branch 2. Both the tellers are simultaneously initiating the cheque clearance activity. Here is how it works:

Step 1: Teller 1 initiates a transfer at 10:30 AM and Teller 2 initiates a transfer at 10:30 AM as well
Step 2: Teller 1’s system checks my bank balance at 10:31 AM and approves the payment because my account has Rs. 12,000 and Teller 2’s system does the same at the same time and approves the payment because the money in my account is more than the value of the cheque I have given.
Step 3: Since both systems feel that there is enough balance in my account, they successfully make the payment.

2 cheques, each worth Rs. 10000/- got paid even though I had only Rs. 12000/- in my bank. Though I am happy about it, clearly the bank is not.

Guess what went wrong here?

There is no synchronization between the two tellers. Practically speaking, two tellers in two different branches don't need to talk to one another before processing a cheque but the banks application should handle such a situation.

All this happened because, the system allowed data related to one persons account to be accessed by two different processes(threads) and also allowed the data to be modified by both those processes at the same time.

This problem is known as a “race condition,” where multiple threads can access the same Car (typically an object’s instance variables), and can produce corrupted data if one thread “races in” too quickly before an operation that should be “atomic” has completed.

Practically speaking, only one of the cheques should have been cleared (whichever teller clicked “Transfer Funds” button first in milliseconds) and the other guys cheque must have bounced. This is exactly what would have happened if the first thread took a lock on the data and processed it, while all other threads that want access to the same data are in line “waiting”. So, by the time the second teller clicked “Transfer funds” his process would have to wait until Teller 1’s transfer is complete and then, the check balance logic would have come back stating “Hey buddy, this bum does not have enough cash to pay this cheque. Bounce this bad boy, will you?”
Now, I guess you know why we need synchronization (Only if you own a bank) but still, we now appreciate the need for synchronization. Lets now look at the details of implementation of this concept.

Preventing the Overpayment of Cheques:

So what can be done? The solution is actually quite simple. We must ensure that the two steps of the transfer—checking the balance and making the transfer—are never split apart. We need them to always be performed as one operation, step 1 and step 2! We call this an “atomic operation” because the operation, regardless of the number of actual statements (or underlying byte code instructions), is completed before any other thread code that acts on the same data.
You can’t guarantee that a single thread will stay running throughout the entire atomic operation. But you can guarantee that even if the thread running the atomic operation moves in and out of the running state, no other running thread will be able to work on the same data. In other words, If Teller 1 falls asleep after checking the balance, we can stop Teller 2 from checking the balance until after Teller 1 wakes up and completes her transfer.

So how do you protect the data? You must do two things:
• Mark the variables private.
• Synchronize the code that modifies the variables.

Remember, you protect the variables in the normal way using an access control modifier. It’s the method code that you must protect, so that only one thread at a time can be executing that code. You do this with the synchronized keyword.

We can solve all of Teller 2 and Teller 1’s problems by adding one word to the code. We mark the makeTransfer() method synchronized as follows:
private synchronized void makeTransfer(int amt) {
if (acct.getBalance() >= amt) {
System.out.println(Thread.currentThread().getName() +
" is going to Transfer");
try {
Thread.sleep(500);
} catch(InterruptedException ex) { }
acct.Transfer(amt);
System.out.println(Thread.currentThread().getName() +
" completes the transfer");
} else {
System.out.println("Not enough in account for "
+ Thread.currentThread().getName()
+ " to Transfer " + acct.getBalance());
}
}

Now we’ve guaranteed that once a thread (Teller 1 or Teller 2) starts the transfer process (by invoking makeTransfer()), the other thread cannot enter that method until the first one completes the process by exiting the method. The new output shows the benefit of synchronizing the makeTransfer() method:

Teller 2 is going to Transfer
Teller 2 completes the transfer
Teller 1 is going to Transfer
Teller 1 completes the transfer
Teller 2 is going to Transfer
Teller 2 completes the transfer
Teller 1 is going to Transfer
Teller 1 completes the transfer
Teller 2 is going to Transfer
Teller 2 completes the transfer
Not enough in account for Teller 1 to Transfer 0
Not enough in account for Teller 2 to Transfer 0
Not enough in account for Teller 1 to Transfer 0
Not enough in account for Teller 2 to Transfer 0
Not enough in account for Teller 1 to Transfer 0

Notice that now both threads, Teller 1 and Teller 2, always check the account balance and complete the transfer before the other thread can check the balance.

Synchronization and Locks

How does synchronization work? The Answer is simple “With locks”. Every object in Java has a built-in lock that only comes into play when the object has synchronized method code. When we enter a synchronized non-static method, we automatically acquire the lock associated with the current instance of the class whose code we’re executing. Acquiring a lock for an object is also known as getting the lock, or locking the object, locking on the object, or synchronizing on the object. We may also use the term monitor to refer to the object whose lock we’re acquiring. Technically the lock and the monitor are two different things, but here we refer to the same thing by those two words.

Since there is only one lock per object, if one thread has picked up the lock, no other thread can pick up the lock until the first thread releases or returns the lock. This means no other thread can enter the synchronized code until the lock has been released. Typically, releasing a lock means the thread holding the lock, in other words, the thread currently in the synchronized method exits the synchronized method. At that point, the lock is free until some other thread enters a synchronized method on that object. Remember the following key points about locking and synchronization:

• Only methods (or blocks) can be synchronized, not variables or classes.
• Each object has just one lock.
• Not all methods in a class need to be synchronized. A class can have both synchronized and non-synchronized methods.
• If two threads are about to execute a synchronized method in a class, and both threads are using the same instance of the class to invoke the method, only one thread at a time will be able to execute the method. The other thread will have to wait until the first one finishes its work. In other words, once a thread acquires the lock on an object, no other thread can enter any of the synchronized methods in that class for that object.
• If a class has both synchronized and non-synchronized methods, multiple threads can still access the class’s non-synchronized methods! If you have methods that don’t access the data you’re trying to protect, then you don’t need to synchronize them. Synchronization can cause a hit in some cases, so you should be careful not to overuse it.
• If a thread goes to sleep, it holds any locks it has—it doesn’t release them.
• A thread can acquire more than one lock. For example, a thread can enter a synchronized method, thus acquiring a lock, and then immediately invoke a synchronized method on a different object, thus acquiring that lock as well. As the methods complete, locks are released again. Also, if a thread acquires a lock and then attempts to call a synchronized method on that same object, no problem. The JVM knows that this thread already has the lock for this object, so the thread is free to call other synchronized methods on the same object, using the lock the thread already has.
• You can synchronize a block of code rather than a method.
Because synchronization does hurt concurrency, you don’t want to synchronize any more code than is necessary to protect your data. So if the scope of a method is more than needed, you can reduce the scope of the synchronized part to something less than a full method to just a block.

We call this, strangely, a synchronized block, and it looks like this:
class TestSyncdBlocks {
public void doSomething() {
System.out.println("not synchronized");
synchronized(this) {
System.out.println("synchronized");
}
}
}

When a thread is executing code from within a synchronized block, including any method code invoked from that synchronized block, the code is said to be executing in a synchronized context.

When you synchronize a method, the object used to invoke the method is the object whose lock must be acquired. But when you synchronize a block of code, you specify which object’s lock you want to use as the lock, so you could, for example, use some third-party object as the lock for this piece of code. That gives you the ability to have more than one lock for code synchronization within a single object.

Or you can synchronize on the current instance (this) as in the code above. Since that’s the same instance that synchronized methods lock on, it means that you could always replace a synchronized method with a non-synchronized method containing a synchronized block. In other words, this:

public synchronized void doSomething() {
System.out.println("synchronized");
}
is equivalent to this:
public void doSomething() {
synchronized(this) {
System.out.println("synchronized");
}
}

These methods both have the exact same effect, in practical terms. The compiled bytecodes may not be exactly the same for the two methods. The first form is shorter and more familiar to most people, but the second can be more flexible.

Static Methods and Synchronization

static methods can be synchronized. There is only one copy of the static data you’re trying to protect, so you only need one lock per class to synchronize static methods, a lock for the whole class. There is such a lock; every class loaded in Java has a corresponding instance of java.lang.Class representing that class. It’s that java.lang.Class instance whose lock is used to protect the static methods of the class (if they’re synchronized). There’s nothing special you have to do to synchronize a static method:

public static synchronized int getSomething() {
return count;
}

Again, this could be replaced with code that uses a synchronized block. If the method is defined in a class called MyClass, the equivalent code is as follows:
public static int getSomething() {
synchronized(MyClass.class) {
return count;
}
}

What’s that MyClass.class that we have used for the sync’d block? That’s called a class literal. It’s a special feature in the Java language that tells the compiler: get me the instance of Class that represents the class called MyClass. You can also do this with the following code:
public static void someMethod() {
Class cl = Class.forName("MyClass");
synchronized (cl) {
// do stuff
}
}

However that’s longer, trickier, and most importantly, not on the SCJP exam. But it’s quick and easy to use a class literal—just write the name of the class, and add .class at the end. No quotation marks needed. Now you’ve got an expression for the Class object you need to synchronize on.

What If a thread cannot get the Lock?

If a thread tries to enter a synchronized method and the lock is already taken, the thread is said to be blocked on the object’s lock. Essentially, the thread goes into a kind of pool for that particular object and has to wait there until the lock is released and the thread can again become runnable/running. Just because a lock is released doesn’t mean any particular thread will get it. There might be several threads waiting for a single lock, for example, and there’s no guarantee that the thread that has waited the longest will get the lock first.
When thinking about blocking, it’s important to pay attention to which objects are being used for locking.

• Threads calling non-static synchronized methods in the same class will only block each other if they’re invoked using the same instance. That’s because they each lock on this instance, and if they’re called using two different instances, they get two locks, which do not interfere with each other.
• Threads calling static synchronized methods in the same class will always block each other—they all lock on the same Class instance.
• A static synchronized method and a non-static synchronized method will not block each other, ever. The static method locks on a Class instance while the non-static method locks on the object instance, these actions do not interfere with each other at all.
• For synchronized blocks, you have to look at exactly what object has been used for locking. Threads that synchronize on the same object will block each other. Threads that synchronize on different objects will not.
A Synopsis of Thread related methods & Lock Availability:
Methods that give up the lock:
a. wait()

Methods that hold the lock:
a. notify()
b. join()
c. sleep()
d. yield()

When to Synchronize?

Synchronization can get pretty complicated, and you may be wondering why you would want to do this at all if you can help it. But remember the earlier “race conditions” example with Teller 1 and Teller 2 making transfers from their account. When we use threads, we usually need to use some synchronization somewhere to make sure our methods don’t interrupt each other at the wrong time and mess up our data. Generally, any time more than one thread is accessing changeable data, you synchronize to protect that data, to make sure two threads aren’t changing it at the same time. You don’t need to worry about local variables—each thread gets its own copy of a local variable. Two threads executing the same method at the same time will use different copies of the local variables, and they won’t trouble each other. However, you do need to worry about static and non-static fields, if they contain data that can be changed.

For changeable data in a non-static field, you usually use a non-static method to access it. By synchronizing that method, you will ensure that any threads trying to run that method using the same instance will be prevented from simultaneous access. But a thread working with a different instance will not be affected, because it’s acquiring a lock on the other instance. That’s what we want, threads working with the same data need to go one at a time, but threads working with different data can just ignore each other and run whenever they want to.

For changeable data in a static field, you usually use a static method to access it. And again, by synchronizing the method you ensure that any two threads trying to access the data will be prevented from simultaneous access, because both threads will have to acquire locks on the Class object for the class the static method’s defined in. Once again, that’s exactly what we want.
However, what if you have a non-static method that accesses a static field? Or a static method that accesses a non-static field (using an instance)? In these cases things start to get tricky quickly, and there’s a very good chance that things will not work the way you want. If you’ve got a static method accessing a non-static field, and you synchronize the method, you acquire a lock on the Class object. But what if there’s another method that also accesses the non-static field, this time using a non-static method? It probably synchronizes on the current instance instead. Remember that a static synchronized method and a non-static synchronized method will not block each other and they can run at the same time. Similarly, if you access a static field using a non-static method, two threads might invoke that method using two different this instances. Which means they won’t block each other, because they use different locks. Which means two threads are simultaneously accessing the same static field, which is exactly the sort of thing we’re trying to prevent.

It gets very confusing trying to imagine all the weird things that can happen here. To keep things simple: in order to make a class thread-safe, methods that access changeable fields need to be synchronized.

Access to static fields should be done from static synchronized methods. Access to non-static fields should be done from non- static synchronized methods. For example:

public class ConfuseMe {
private static int staticField;
private int nonstaticField;
public static synchronized int getStaticField() {
return staticField;
}
public static synchronized void setStaticField(int staticField) {
ConfuseMe.staticField = staticField;
}
public synchronized int getNonstaticField() {
return nonstaticField;
}
public synchronized void setNonstaticField(int nonstaticField) {
this.nonstaticField = nonstaticField;
}
}

What if you need to access both static and non-static fields in a method? Well, there are ways to do that, but it’s beyond what you need for the exam. So, for now, your are off the hook and don't need to bother much about this complicated thing that's going to make our lives harder than it already is…

Thread Safe Classes

When a class has been carefully synchronized to protect its data, we say the class is “thread-safe.” Many classes in the Java APIs already use synchronization internally in order to make the class “thread-safe.” For example, StringBuffer and StringBuilder are nearly identical classes, except that all the methods in StringBuffer are synchronized when necessary, while those in StringBuilder are not. Generally, this makes StringBuffer safe to use in a multithreaded environment, while StringBuilder is not. However, even when a class is “thread-safe,” it is often dangerous to rely on these classes to provide the thread protection you need. You still need to think carefully about how you use these classes, As an example, consider the following class.

import java.util.*;
public class ThreadSafeClass {
private List names = Collections.synchronizedList(new LinkedList());
public void addName(String name) {
names.addName(name);
}
public String removeName() {
if (names.size() > 0)
return (String) names.remove(0);
else
return null;
}
}

The method Collections.synchronizedList() returns a List whose methods are all synchronized and “thread-safe” according to the java API documentation. The question is, can the ThreadSafeClass class be used safely from multiple threads? It’s tempting to think that yes, since the data in names is in a synchronized collection, the ThreadSafeClass class is “safe” too. However that’s not the case—the removeName() may sometimes throw a NoSuchElementException. What’s the problem? Doesn’t it correctly check the size() of names before removing anything, to make sure there’s something there? How could this code fail? Let’s try to use ThreadSafeClass like this:

public static void main(String[] args) {
final ThreadSafeClass nl = new ThreadSafeClass();
nl.addName("Rocky");
class NameDropper extends Thread {
public void run() {
String name = nl.removeName();
System.out.println(name);
}
}
Thread t1 = new NameDropper();
Thread t2 = new NameDropper();
t1.start();
t2.start();
}

What might happen here is that one of the threads will remove the one name and print it, then the other will try to remove a name and get null. If we think just about the calls to names.size() and names.get(0), they occur in this order:

Thread t1 executes names.size(), which returns 1.
Thread t1 executes names.remove(0), which returns Rocky.
Thread t2 executes names.size(), which returns 0.
Thread t2 does not call remove(0).
The output here is
Rocky
null

However, if we run the program again something different might happen:

Thread t1 executes names.size(), which returns 1.
Thread t2 executes names.size(), which returns 1.
Thread t1 executes names.remove(0), which returns Rocky.
Thread t2 executes names.remove(0), which throws an exception because the list is now empty.

The thing to realize here is that in a “thread-safe” class like the one returned by synchronizedList(), each individual method is synchronized. So names.size() is synchronized, and names.remove(0) is synchronized. But nothing prevents another thread from doing something else to the list in between those two calls. And that’s when unexpected things can happen.
There’s a solution here: don’t rely on Collections.synchronizedList(). Instead, synchronize the code yourself:

import java.util.*;
public class ThreadSafeClass {
private List names = new LinkedList();
public synchronized void addName(String name) {
names.addName(name);
}
public synchronized String removeName() {
if (names.size() > 0)
return (String) names.remove(0);
else
return null;
}
}

Now the entire removeName() method is synchronized, and once one thread starts it and calls names.size(), there’s no way the other thread can cut in and steal the last name. The other thread will just have to wait until the first thread completes the removeName() method.
The moral of the story is (Like in the Value Education class in School) that just because a class is described as “thread-safe” doesn’t mean it is always thread-safe. If individual methods are synchronized, that may not be enough, you may be better off putting in synchronization logic yourself. Once you do that, the original synchronization may well become redundant.

I know that we never paid attention to the Value Education class in school, but my friend, here the moral is very important and you need to pay attention in order to pass the exam. So, do me a favor, go back to the paragraph above and read it once before you move ahead to the next topic…


Deadlocks

Perhaps the scariest thing that can happen to a Java program is deadlock. Deadlock occurs when two threads are blocked, with each waiting for the one another’s lock. Neither can run until the other gives up its lock, so they’ll sit there forever.

This can happen, for example, when thread A hits synchronized code, acquires a lock B, and then enters another method that’s also synchronized. But thread A can’t get the lock to enter this synchronized code block C because another thread D has the lock already. So thread A goes off to the “waiting for the C lock” pool, hoping that thread D will finish up its work and release the lock. But thread A will wait forever, because while thread D picked up lock C, it then entered a method synchronized on lock B. Obviously, thread D can’t get the lock B because thread A has it. And thread A won’t release it until thread D releases lock C. But thread D won’t release lock C until after it can get lock B and continue. And there they are – Stubbornly waiting for the other person to give up the lock. The following example demonstrates deadlock:

1. public class DeadlockExample {
2. private static class Car {
3. public int value;
4. }
5. private Car CarA = new Car();
6. private Car CarB = new Car();
7. public int read() {
8. synchronized(CarA) { // 1
9. synchronized(CarB) {
10. return CarB.value + CarA.value;
11. }
12. }
13. }
14.
15. public void write(int a, int b) {
16. synchronized(CarB) { // 2
17. synchronized(CarA) {
18. CarA.value = a;
19. CarB.value = b;
20. }
21. }
22. }
23. }

The lines marked with //1 and //2 are the places where we might end up with a deadlock.
Assume that read() is started by one thread and write() is started by another. If there are two different threads that may read and write independently, there is a risk of deadlock at line 8 or 16. The reader thread will have CarA, the writer thread will have CarB, and both will get stuck waiting for the other.

Code like this almost never results in deadlock because the CPU has to switch from the reader thread to the writer thread at a particular point in the code, and the chances of deadlock occurring are very small. The application may work fine most of the time.

The preceding simple example is easy to fix; just swap the order of locking for either the reader or the writer at lines 16 and 17 (or lines 8 and 9). More complex deadlock situations can take a long time to figure out and even longer to solve.

Regardless of how little chance there is for your code to deadlock, the bottom line is, if you get a deadlock, you’re dead. There are design approaches that can help avoid deadlock, including strategies for always acquiring locks in a particular order.

But that’s something you don't need for the exam.

Exam Tip:
Deadlocks are almost like stubborn fighting couples. Both parties are upset with each other and are silent and not willing to talk to one another. Unless one party speaks up and apologizes the other is going to stay silent. Fortunately we humans have emotions and most often one party apologizes and then the couples are happily married again. Unfortunately threads arent human and don't have any emotions. If one waits for the other to speak up, it waits and waits and waits. So, a smart programmer will take all possible steps to ensure that doesn't happen in his code, which I am sure you will!!!


Previous Chapter: Chapter 59 - Thread Prioritoes, yield and join methods

Next Chapter: Chapter 61 - Thread Interactions

Chapter 59: Thread Priorities, yield( ) and Join

The last chapter in the series of chapters on Threads is going to be about thread priorities and using the yield() & join() methods. I know you are eager to finish off threads on the SCJP syllabus, so am I.

So, lets get started!!!

Thread Priorities

Threads always run with some priority, usually represented as a number between 1 and 10 (although in some cases the range is less than 10). The scheduler in most JVMs uses preemptive, priority-based scheduling (which implies some sort of time slicing). This does not mean that all JVMs use time slicing. The JVM specification does not require a VM to implement a time-slicing scheduler, where each thread is allocated a fair amount of time and then sent back to runnable to give another thread a chance. Although many JVMs do use time slicing, some may use a scheduler that lets one thread stay running until the thread completes its run() method.

In most JVMs, however, the scheduler does use thread priorities in one important way: If a thread enters the runnable state, and it has a higher priority than any of the threads in the pool and a higher priority than the currently running thread, the lower-priority running thread usually will be bumped back to runnable and the highest-priority thread will be chosen to run. In other words, at any given time the currently running thread usually will not have a priority that is lower than any of the threads in the pool. In most cases, the running thread will be of equal or greater priority than the highest priority threads in the pool. This is as close to a guarantee about scheduling as you’ll get from the JVM specification, which means, you must or rather you can never rely on thread priorities to guarantee the correct behavior of your program.

What is also not guaranteed is the behavior when threads in the pool are of equal priority, or when the currently running thread has the same priority as threads in the pool. All priorities being equal, a JVM implementation of the scheduler is free to do just about anything it likes. That means a scheduler is gonna be just like your boss as explained in the previous chapter. The scheduler might do one of the following:

• Pick a thread to run, and run it there until it blocks or completes.
• Time slice the threads in the pool to give everyone an equal opportunity to run.

Setting a Thread’s Priority

A thread gets a default priority that is the priority of the thread of execution that creates it. For example, in the code
public class TestMyNewThreads {
public static void main (String [] args) {
MyNewThread t = new MyNewThread();
}
}

The thread referenced by t will have the same priority as the main thread, since the main thread is executing the code that creates the MyNewThread instance.

You can also set a thread’s priority directly by calling the setPriority() method on a Thread instance as follows:
MyNewThread1 r = new MyNewThread1();
Thread t = new Thread(r);
t.setPriority(8);
t.start();

Priorities are set using a positive integer, usually between 1 and 10, and the JVM will never change a thread’s priority. However, the values 1 through 10 are not guaranteed. Some JVM’s might not recognize ten distinct values. Such a JVM might merge values from 1 to 10 down to maybe values from 1 to 5, so if you have, say, ten threads each with a different priority, and the current application is running in a JVM that allocates a range of only five priorities, then two or more threads might be mapped to one priority.

Although the default priority is 5, the Thread class has the three following constants (static final variables) that define the range of thread priorities:

Thread.MIN_PRIORITY (1)
Thread.NORM_PRIORITY (5)
Thread.MAX_PRIORITY (10)


The yield( ) Method

So what does the static Thread.yield() have to do with all this? Not that much, actually. What yield() is supposed to do is make the currently running thread go back to runnable to allow other threads of the same priority to get their turn. So the intention to use yield() is to allow graceful turn-taking among equal-priority threads. In reality, though, the yield() method isn’t guaranteed to do what it claims, and even if yield() does cause a thread to step out of running and back to runnable, there’s no guarantee the yielding thread won’t just be chosen again over all the others! So while yield() might and often does make a running thread give up its slot to another runnable thread of the same priority, but there’s no guarantee.
A yield() won’t ever cause a thread to go to the waiting/sleeping/ blocking state. At most, a yield() will cause a thread to go from running to runnable, but again, it might have no effect at all.


The join( ) Method

The non-static join() method of class Thread lets one thread “join onto the end” of another thread. If you have a thread B that can’t do its work until another thread A has completed its work, then you want thread B to “join” thread A. This means that thread B will not become runnable until A has finished (and entered the dead state).

Thread t = new Thread();
t.start();
t.join();

The preceding code takes the currently running thread (if this were in the main() method, then that would be the main thread) and joins it to the end of the thread referenced by t. This blocks the current thread from becoming runnable until after the thread referenced by t is no longer alive. In other words, the code t.join() means “Join me (the current thread) to the end of t, so that t must finish before I (the current thread) can run again.” You can also call one of the overloaded versions of join() that takes a timeout duration, so that you’re saying, “wait until thread t is done, but if it takes longer than 5,000 milliseconds, then stop waiting and become runnable anyway.”

So far we’ve looked at three ways a running thread could leave the running state:
• A call to sleep() Guaranteed to cause the current thread to stop executing for at least the specified sleep duration (although it might be interrupted before its specified time).
• A call to yield() Not guaranteed to do much of anything, although typically it will cause the currently running thread to move back to runnable so that a thread of the same priority can have a chance.
• A call to join() Guaranteed to cause the current thread to stop executing until the thread it joins with (in other words, the thread it calls join() on) completes, or if the thread it’s trying to join with is not alive, however, the current thread won’t need to back out.
Besides those three, we also have the following scenarios in which a thread might leave the running state:
• The thread’s run() method completes.
• A call to wait() on an object.
• A thread can’t acquire the lock on the object whose method code it’s attempting to run.
• The thread scheduler can decide to move the current thread from running to runnable in order to give another thread a chance to run. No reason is needed—the thread scheduler can trade threads in and out whenever it likes.

Previous Chapter: Chapter 58 - Preventing Thread Execution

Next Chapter: Chapter 60 - Synchronization

Chapter 58: Preventing Thread Execution

In the previous chapters we saw what a thread is and how to run or execute them. But, there is one more important thing that we need to know. Let me give a clue. Lets say you have multiple threads and you want one of your threads to finish before the others. It would definitely be sweet to alter the way our threads run and finish, wouldn't it? That is exactly what we are going to learn in this chapter.

Before we begin, I repeat something I said earlier.
WE CANNOT AND I MEAN CANNOT GUARANTEE THE WAY THREADS EXECUTE IN OUR PROGRAM.

We can only request the scheduler to run the threads the way we want but that by no means is guarantee. Think of the scheduler as your hard headed boss who ends up irritating you even if you try out of your way to please him. Though it's a bad analogy, that's exactly how the scheduler works. Stubborn and all by itself and not listening to anyone.

Lets get started!!!

Stopping a Thread from Executing

A thread that’s been stopped usually means a thread that’s moved to the dead state. But you should be able to recognize when a thread will get kicked out of running but not be sent back to either runnable or dead.

For the purpose of the exam, we aren’t concerned with a thread blocking on I/O (say, waiting for something to arrive from an input stream from the server). We are concerned with the following:
• Sleeping
• Waiting
• Blocked because it needs an object’s lock

Sleeping

The sleep() method is a static method of class Thread. You use it in your code to “slow a thread down” by forcing it to go into a sleep mode before coming back to runnable. When a thread sleeps, it drifts off somewhere and doesn’t return to runnable until it wakes up.

So why would you want a thread to sleep? Well, you might think the thread is moving too quickly through its code. Or you might need to force your threads to take turns, since reasonable turn-taking isn’t guaranteed in the Java specification.

You do this by invoking the static Thread.sleep() method, giving it a time in milliseconds as follows:
try {
Thread.sleep(5*1000); // Sleep for 5 seconds
} catch (InterruptedException ex) { }

Notice that the sleep() method can throw a checked InterruptedException (you’ll usually know if that is a possibility, since another thread has to explicitly do the interrupting), so you must acknowledge the exception with a handle or declare. Typically, you wrap calls to sleep() in a try/catch, as in the preceding code.

Let’s modify our Rocky, Cena, Triple H code by using sleep() to try to force the threads to alternate rather than letting one thread dominate for any period of time. Where do you think the sleep() method should go?

class NameRunnable implements Runnable {

public void run() {

for (int x = 1; x < 4; x++) {

System.out.println("Run by "

+ Thread.currentThread().getName());

try {

Thread.sleep(1000);

} catch (InterruptedException ex) { }

}

}

}


public class SleepExample {

public static void main (String [] args) {


// Make one Runnable

NameRunnable nr = new NameRunnable();


Thread one = new Thread(nr);

one.setName("Rocky");

Thread two = new Thread(nr);

two.setName("Cena");

Thread three = new Thread(nr);

three.setName("Triple H");


one.start();

two.start();

three.start();

}

}

Running this code shows Rocky, Cena, and Triple H alternating nicely:

% java SleepExample

Run by Rocky

Run by Cena

Run by Triple H

Run by Rocky

Run by Cena

Run by Triple H

Run by Rocky

Run by Cena

Run by Triple H


Just keep in mind that the behavior in the preceding output is still not guaranteed. You can’t be certain how long a thread will actually run before it gets put to sleep, so you can’t know with certainty that only one of the three threads will be in the runnable state when the running thread goes to sleep. In other words, if there are two threads awake and in the runnable pool, you can’t know with certainty that the least recently used thread will be the one selected to run. Still, using sleep() is the best way to help all threads get a chance to run! Or at least to guarantee that one thread doesn’t get in and stay until it’s done. When a thread encounters a sleep call, it must go to sleep for at least the specified number of milliseconds (unless it is interrupted before its wake-up time, in which case it immediately throws the InterruptedException).

Exam Tip: Just because a thread’s sleep() expires, and it wakes up, does not mean it will return to running! Remember, when a thread wakes up, it simply goes back to the runnable state. So the time specified in sleep() is the minimum duration in which the thread won’t run, but it is not the exact duration in which the thread won’t run. So you can’t, for example, rely on the sleep() method to give you a perfectly accurate timer. Although in many applications using sleep() as a timer is certainly good enough, you must know that a sleep() time is not a guarantee that the thread will start running again as soon as the time expires and the thread wakes

Remember that sleep() is a static method, so don’t be fooled into thinking that one thread can put another thread to sleep. You can put sleep() code anywhere, since all code is being run by some thread. When the executing code (meaning the currently running thread’s code) hits a sleep() call, it puts the currently running thread to sleep.

Previous Chapter: Chapter 57 - Thread States & Transitions

Next Chapter: Chapter 59 - Thread Priorities, yield and join

Chapter 56: Threads and Multithreading

This chapter and the subsequent ones on Threads and Multi-threading is probably by far the most complex topic we will be covering as part of our aim at getting a SCJP Certification.
Before we begin – let me put out a Disclaimer…

Disclaimer: This chapter makes almost no attempt to teach you how to design a good, safe, multithreaded application. The concepts covered in this article are just the tip of the iceberg and you’re here only to learn the basics of threading, and what you need to get through the thread questions on the exam. Before you can write decent multithreaded code, however, you really need to study more on the complexities and subtleties of multithreaded code.

In a single-threaded runtime environment, actions execute one after another. The next action can happen only when the previous one is finished. If task A takes half an hour, and the user wants to do something else, he is doomed to wait until task A is over.

Ideally, the user should be able to carry on with his other task until his first task is complete. Imagine having to wait till your eclipse build all your source code before you could check your email? Thankfully windows uses multiple threads to run your eclipse and outlook. So you don't have to go through this pain. Similarly java has options wherein the programmer can have multiple threads of execution running.

Now you are ready to dive into the magical or rather complicated world of threads.

Lets get started!!!

What is a Thread?

In Java, “thread” means:
• A thread of execution

A thread of execution is an individual process that has its own call stack. In Java, there is one thread per call stack or, to think of it in reverse, one call stack per thread. Even if you don’t create any new threads in your program, threads are there running without your knowledge.
If you are curious and ask me how? Just stop for a moment and think how you would execute a java program? You’ll write a main method and then execute it from the command line using the “java” command. Well, you have already answered the question because, when your main method starts, the JVM assigns a thread for this main method and assigns it a call stack. So, eventhough you did not intentionally create a thread, the system did one for you.

The most important concept to understand from this entire chapter is this:

When it comes to threads, very little is guaranteed.

So be very cautious about interpreting the behavior you see on one machine as “the way threads work.” The exam expects you to know what is and is not guaranteed behavior, so that you can design your program in such a way that it will work regardless of the underlying JVM.

Exam Tip:
The thread questions are among the most difficult questions on the exam. In fact, for most people they are the toughest questions on the exam. If you’re not already familiar with threads, you’ll probably need to spend some time experimenting.
Exam Tip:
The topic of daemon threads is NOT on the exam. All of the threads discussed in this chapter are “user” created threads. We can create a second kind of thread called a daemon thread. The difference between these two types of threads (user and daemon) is that the JVM exits an application only when all user threads are complete—the JVM doesn’t care about letting daemon threads complete, so once all user threads are complete, the JVM will shut down, regardless of the state of any daemon threads. Once again, this topic is NOT on the exam and it is enough if you know this much about daemon threads for the exam.

Creating a Thread

A thread in Java begins as an instance of java.lang.Thread. You’ll find methods in the Thread class for managing threads including creating, starting, and pausing them. They are:
start()
yield()
sleep()
run()

All the awesome action happens in the run() method. Think of the code you want to execute in a separate thread as the job to do. Lets say, you have some work that needs to be done, in the background while other things are happening in the program, so what you really want is that work to be executed in its own thread. All that code you want executed in a separate thread goes into the run() method.

Ex:
public void run() {
// your job code goes here
}

The run() method will call other methods, of course, but the thread of execution—the new call stack—always begins by invoking run(). So where does the run() method go? In one of the two classes you can use to define your thread job.

You can define and instantiate a thread in one of two ways:
• Extend the java.lang.Thread class.
• Implement the Runnable interface.

You need to know about both for the exam, although I would personally recommend that you implement Runnable than extend Thread. Extending the Thread class is the easiest, but it’s usually not a good OO practice.

Now, you may ask me “Why? Why should I choose the Runnable over Thread?”
Well, if you thought of the why before reading the preceding line, give yourself a pat on the back. Well done!

Because, if you extend the Thread class what would you do if you have to extend another concrete parent class that has vital/important behavior that you need in your class? Get the point? Java does not support direct multiple inheritance and hence, once you extend the Thread class, you are done, for good. You cannot extend any other class. That is why I recommended the Runnable interface. Even if you implement the interface, you are free to extend any class you want. Convenient, right?

Defining a Thread

To define a thread, you need a place to put your run() method, and as we just discussed, you can do that by extending the Thread class or by implementing the Runnable interface. We’ll look at both in this section.

Extending java.lang.Thread
The simplest way to define code to run in a separate thread is to
• Extend the java.lang.Thread class.
• Override the run() method.
It looks like this:
class MyFirstThread extends Thread {
public void run() {
System.out.println("Important job running in MyFirstThread");
}
}
The limitation with this approach is that if you extend Thread, you can’t extend anything else. And it’s not as if you really need that inherited Thread class behavior, because in order to use a thread you’ll need to instantiate one anyway.

Keep in mind that you’re free to overload the run() method in your Thread subclass:
class MyFirstThread extends Thread {
public void run() {
System.out.println("Important job running in MyFirstThread");
}
public void run(String s) {
System.out.println("String running is " + s);
}
}

Note: The overloaded run(String s) method will be ignored by the Thread class unless you call it yourself. The Thread class expects a run() method with no arguments, and it will execute this method for you in a separate call stack after the thread has been started. With a run(String s) method, the Thread class won’t call the method for you, and even if you call the method directly yourself, execution won’t happen in a new thread of execution with a separate call stack. It will just happen in the same call stack as the code that you made the call from, just like any other normal method call.


Implementing java.lang.Runnable

Implementing the Runnable interface gives you a way to extend any class you like, but still define behavior that will be run by a separate thread. It looks like this:

class MyFirstRunnableClass implements Runnable {
public void run() {
System.out.println("Imp job running in MyFirstRunnableClass");
}
}
Regardless of which mechanism you choose, you’ve now got yourself some code that can be run by a thread of execution. So now let’s take a look at instantiating your thread-capable class, and then we’ll figure out how to actually get the thing running.

Instantiating a Thread

Remember, every thread of execution begins as an instance of class Thread. Regardless of whether your run() method is in a Thread subclass or a Runnable implementation class, you still need a Thread object to do the work.

If you extended the Thread class, instantiation is dead simple:
MyFirstThread t = new MyFirstThread()

If you implement Runnable, instantiation is only slightly less simple. To have code run by a separate thread, you still need a Thread instance. But rather than combining both the thread and the run() method into one class, you’ve split it into two classes—the Thread class for the thread-specific code and your Runnable implementation class for your job-that-should-be-run-by-a-thread code.

First, you instantiate your Runnable class:
MyFirstRunnableClass r = new MyFirstRunnableClass();

Next, you get yourself an instance of java.lang. Thread, and you give it your job!
Thread t = new Thread(r); // Pass your Runnable to the Thread

If you create a thread using the no-arg constructor, the thread will call its own run() method when it’s time to start working. That’s exactly what you want when you extend Thread, but when you use Runnable, you need to tell the new thread to use your run() method rather than its own. The Runnable you pass to the Thread constructor is called the target or the target Runnable.
You can pass a single Runnable instance to multiple Thread objects, so that the same Runnable becomes the target of multiple threads, as follows:

public class TestMyThreads {
public static void main (String [] args) {
MyFirstRunnableClass r = new MyFirstRunnableClass();
Thread aaa = new Thread(r);
Thread bbb = new Thread(r);
Thread ccc = new Thread(r);
}
}

Giving the same target to multiple threads means that several threads of execution will be running the very same job and that same job will be done multiple times.

Exam Tip:
The Thread class itself implements Runnable. (After all, it has a run() method that we were overriding.) This means that you could pass a Thread to another Thread’s constructor:
Thread t = new Thread(new MyFirstThread());

This is a bit silly, but it’s legal. In this case, you really just need a Runnnable, and creating a whole other Thread is overkill.

Besides the no-arg constructor and the constructor that takes a Runnable (the target, i.e., the instance with the job to do), there are other overloaded constructors in class Thread. The constructors we care about are
• Thread()
• Thread(Runnable target)
• Thread(Runnable target, String name)
• Thread(String name)

You need to recognize all of them for the exam! Don't worry, we’ll discuss some of the other constructors in the preceding list a little later.

So now you’ve made yourself a Thread instance, and it knows which run() method to call. But nothing is happening yet. At this point, all we’ve got is a Java object of type Thread. It is not yet a thread of execution. To get an actual thread and a new call stack—we still have to start the thread.

When a thread has been instantiated but not started (in other words, the start() method has not been invoked on the Thread instance), the thread is said to be in the new state. At this stage, the thread is not yet considered to be alive. Once the start() method is called, the thread is considered to be alive (even though the run() method may not have actually started executing yet). A thread is considered dead (no longer alive) after the run() method completes. The isAlive() method is the best way to determine if a thread has been started but has not yet completed its run() method.

Note: The getState() method is very useful for debugging, but you won’t get any questions about it in the exam.

Starting a Thread

You’ve created a Thread object and it knows its target. Now it’s time to get the whole thread thing running. It’s pretty straight forward:
t.start();

Prior to calling start() on a Thread instance, the thread (when we use lowercase t, we’re referring to the thread of execution rather than the Thread class) is said to be in the new state as we said. The new state means you have a Thread object but you don’t yet have a true thread. So what happens after you call start()?

• A new thread of execution starts (with a new call stack).
• The thread moves from the new state to the runnable state.
• When the thread gets a chance to execute, its target run() method will run.

Be sure you remember the following: You start a Thread, not a Runnable. You call start() on a Thread instance, not on a Runnable instance. The following example demonstrates what we’ve covered so far—defining, instantiating, and starting a thread:



class TestRunnable implements Runnable {

public void run() {

for(int x = 1; x < 6; x++) {
System.out.println("Runnable running");

}

}

}



public class TestMyThreads {

public static void main (String [] args) {

TestRunnable r = new TestRunnable();

Thread t = new Thread(r);

t.start();

}

}



Running the preceding code prints out exactly what you’d expect:

% java TestMyThreads

Runnable running

Runnable running

Runnable running

Runnable running

Runnable running


Exam Tip: There’s nothing special about the run() method as far as Java is concerned. Like main(), it just happens to be the name (and signature) of the method that the new thread knows to invoke. So if you see code that calls the run() method on a Runnable (or even on a Thread instance), that’s perfectly legal. But it doesn’t mean the run() method will run in a separate thread! Calling a run() method directly just means you’re invoking a method from whatever thread is currently executing, and the run() method goes onto the current call stack rather than at the beginning of a new call stack. The following code does not start a new thread of execution:
Thread t = new Thread();
t.run();
The run method will be executed but there will be no new Thread.

So what happens if we start multiple threads? We’ll run a simple example in a moment, but first we need to know how to print out which thread is executing. We can use the getName() method of class Thread, and have each Runnable print out the name of the thread executing that Runnable object’s run() method. The following example instantiates a thread and gives it a name, and then the name is printed out from the run() method:

class TestRunnableWithNames implements Runnable {
public void run() {
System.out.println("TestRunnableWithNames running");
System.out.println("Run by "
+ Thread.currentThread().getName());
}
}
public class NameThread {
public static void main (String [] args) {
TestRunnableWithNames nr = new TestRunnableWithNames();
Thread t = new Thread(nr);
t.setName("Rocky");
t.start();
}
}

Running this code produces the following, extra special, output:

% java NameThread
TestRunnableWithNames running
Run by Rocky

To get the name of a thread you call getName() on the Thread instance. But the target Runnable instance doesn’t even have a reference to the Thread instance, so we first invoked the static Thread.currentThread() method, which returns a reference to the currently executing thread, and then we invoked getName() on that returned reference.

Even if you don’t explicitly name a thread, it still has a name. Let’s look at the previous code, commenting out the statement that sets the thread’s name:

public class NameThread {
public static void main (String [] args) {
TestRunnableWithNames nr = new TestRunnableWithNames();
Thread t = new Thread(nr);
// t.setName("Rocky");
t.start();
}
}
Running the preceding code now gives us
% java NameThread
TestRunnableWithNames running
Run by Thread-0

And since we’re getting the name of the current thread by using the static Thread.currentThread() method, we can even get the name of the thread running our main code,
public class NameThreadTwo {
public static void main (String [] args) {
System.out.println("thread is "
+ Thread.currentThread().getName());
}
}

which prints out
% java NameThreadTwo
thread is main

That’s right, the main thread already has a name—main.


Starting and Running Multiple Threads


Let’s actually get down to business and get multiple threads going (more than two, that is). We already had two threads, because the main() method starts in a thread of its own, and then t.start() started a second thread. Now we’ll do more. The following code creates a single Runnable instance and three Thread instances. All three Thread instances get the same Runnable instance, and each thread is given a unique name. Finally, all three threads are started by invoking start() on the Thread instances.



class TestRunnableWithNames implements Runnable {

public void run() {

for (int x = 1; x <= 3; x++) {
System.out.println("Run by "

+ Thread.currentThread().getName()

+ ", x is " + x);

}

}

}

public class ManyNames {

public static void main(String [] args) {

// Make one Runnable

TestRunnableWithNames nr = new TestRunnableWithNames();

Thread one = new Thread(nr);

Thread two = new Thread(nr);

Thread three = new Thread(nr);



one.setName("Rocky");

two.setName("Cena");

three.setName("Triple H");

one.start();

two.start();

three.start();

}

}

Running this code might produce the following:



% java ManyNames

Run by Rocky, x is 1

Run by Triple H, x is 1

Run by Rocky, x is 2

Run by Cena, x is 1

Run by Rocky, x is 3

Run by Cena, x is 2

Run by Cena, x is 3

Run by Triple H, x is 2

Run by Triple H, x is 3



Well, at least that’s what it printed when we ran it—this time, on our machine. But the behavior you see above is not guaranteed. I repeat, “THE BEHAVIOR IS NOT GUARANTEED.” You need to know, for your future as a Java programmer as well as for the exam, that there is nothing in the Java specification that says threads will start running in the order in which they were started (in other words, the order in which start() was invoked on each thread). And there is no guarantee that once a thread starts executing, it will keep executing until it’s done. Or that a loop will complete before another thread begins. Nothing is guaranteed in the preceding code except this:


Each thread will start, and each thread will run to completion.


Within each thread, things will happen in a predictable order. But the actions of different threads can mix together in unpredictable ways. If you run the program multiple times, or on multiple machines, you may see different output. Even if you don’t see different output, you need to realize that the behavior you see is not guaranteed. Sometimes a little change in the way the program is run will cause a difference to emerge. Just for fun we bumped up the loop code so that each run() method ran the for loop 400 times rather than 3, and eventually we did start to see some wobbling:




public void run() {

for (int x = 1; x <= 400; x++) {
System.out.println("Run by "

+ Thread.currentThread().getName()

+ ", x is " + x);

}

}



Running the preceding code, with each thread executing its run loop 400 times, started out fine but then became nonlinear. Here’s just a snip from the command-line output of running that code:

Run by Rocky, x is 345

Run by Triple H, x is 313

Run by Cena, x is 341

Run by Triple H, x is 314

Run by Cena, x is 342

Run by Triple H, x is 315

Run by Rocky, x is 346

Run by Cena, x is 343

Run by Rocky, x is 347

Run by Cena, x is 344

And so on…


Notice that there’s not really any clear pattern here. If we look at only the output from Rocky, we see the numbers increasing one at a time, as expected:

Run by Rocky, x is 345

Run by Rocky, x is 346

Run by Rocky, x is 347



And similarly if we look only at the output from Cena, or Triple H. Each one individually is behaving in a nice orderly manner. But together, it is utter chaos! In the fragment above we see Rocky, then Cena, then Triple H (in the same order we originally started the threads), but then Cena moves in when it was Rocky’s turn. And then Triple H and Cena trade back and forth for a while until finally Rocky gets another chance. They jump around like this for a while after this. Eventually (after the part shown above) Rocky finishes, then Triple H, and finally Cena finishes with a long sequence of output. So even though Triple H was started third, he actually completed second. And if we run it again, we’ll get a different result.


Why?


Because it’s up to the scheduler, and we don’t control the scheduler! Which brings up another key point to remember: Just because a series of threads are started in a particular order doesn’t mean they’ll run in that order. For any group of started threads, order is not guaranteed by the scheduler. And duration is not guaranteed. You don’t know, for example, if one thread will run to completion before the others have a chance to get in or whether they’ll all take turns nicely, or whether they’ll do a combination of both.


A thread is no longer a thread when its run() method completes execution.


When a thread completes its run() method, the thread ceases to be a thread of execution. The stack for that thread dissolves, and the thread is considered dead. Not dead and gone, but, just dead. It’s still a Thread object, just not a thread of execution. So if you’ve got a reference to a Thread instance, then even when that Thread instance is no longer a thread of execution, you can still call methods on the Thread instance, just like any other Java object. What you can’t do, though, is call start() again.


Once a thread has been started, it can never be started again.


If you have a reference to a Thread, and you call start(), it’s started. If you call start() a second time, it will cause an exception (an IllegalThreadStateException, which is a kind of RuntimeException, but you don’t need to worry about catching it). This happens whether or not the run() method has completed from the first start() call. Only a new thread can be started, and then only once. A runnable thread or a dead thread cannot be restarted.



Exam Tip: In addition to using setName() and getName to identify threads, you might see getld(). The getld() method returns a positive, unique, long number, and that number will be that thread’s only ID number for the thread’s entire life

The Thread Scheduler

The thread scheduler is the part of the JVM that decides which thread should run at any given moment, and also takes threads out of the run state. Assuming a single processor machine, only one thread can actually run at a time. Only one stack can ever be executing at one time. And it’s the thread scheduler that decides which thread among all other eligible threads will actually run. When I say eligible, it means threads that are in the runnable state.

Any thread in the runnable state can be chosen by the scheduler to be the one and only running thread. If a thread is not in a runnable state, then it cannot be chosen to be the currently running thread. And, to repeat something I have already said:

THE ORDER IN WHICH RUNNABLE THREADS ARE CHOSEN TO RUN IS NOT AND I MEAN IS NOT GUARANTEED!


Although we don’t control the thread scheduler, we can sometimes influence it. The following methods give us some tools for influencing the scheduler. Just don’t ever mistake influence for control.

Exam Tip: Expect to see exam questions that look for your understanding of what is and is not guaranteed! You must be able to look at thread code and determine whether the output is guaranteed to run in a particular way or is indeterminate

Methods from the java.lang.thread Class

Some of the methods that can help us influence thread scheduling are as follows:
public static void sleep(long millis) throws InterruptedException
public static void yield()
public final void join() throws InterruptedException
public final void setPriority(int newPriority)

Note that both sleep() and join() have overloaded versions which not shown here.

Methods from the java.lang.object Class

Every class in Java inherits the following three thread-related methods:
public final void wait() throws InterruptedException
public final void notify()
public final void notifyAll()

The wait() method has three overloaded versions (including the one listed here).

Don't worry too much about the functionalities of these methods because we are going to have a full chapter dedicated to these babies.

For now, the chapter is over. You can give a sigh of relief which is exactly what I am doing now.. Huh!!!

Previous Chapter: Self Test - Chapters 52 to 55

Next Chapter: Thread States & Transition

Chapter 55: Static Inner Classes

In the chapter on Inner classes, I had promised that we will look in more detail about the different types of inner classes. Well here we are. This is the last and final type of inner classes. “Static” Inner Classes.

So, without any further delays, lets get Started!!!

Static Inner Classes

Actually static inner classes aren’t inner classes at all, by the standard definition of an inner class. While an inner class enjoys that special relationship with the outer class (or rather the instances of the two classes share a relationship), a static MyStaticExInnerClass class does not. It is simply a non-inner (also called “top-level”) class scoped within another. So with static classes it’s really more about name-space resolution than about an implicit relationship between the two classes.

A static MyStaticExInnerClass class is simply a class that’s a static member of the enclosing class:
class MyExOuter {
static class StaticInner { }
}

The class itself isn’t really “static”; there’s no such thing as a static class. The static modifier in this case says that the MyStaticExInnerClass class is a static member of the outer class. That means it can be accessed, as with other static members, without having an instance of the outer class.

Instantiating and Using Static Inner Classes

You use standard syntax to access a static MyStaticExInnerClass class from its enclosing class. The syntax for instantiating a static MyStaticExInnerClass class from a non-enclosing class is a little different from a normal inner class, and looks like this:

class MyExOuter {
static class MyStaticExInner {void do() { System.out.println("hi"); } }
}
class Test {
static class B2 {void goB2() { System.out.println("hi 2"); } }
public static void main(String[] args) {
MyExOuter.MyStaticExInner n = new MyExOuter.MyStaticExInner();
n.do();
B2 b2 = new B2();
b2.goB2();
}
}
Which produces
hi
hi 2

Exam Tip:
Just as a static method does not have access to the instance variables and nonstatic methods of the class, a static Inner class does not have access to the instance variables and nonstatic methods of the outer class. Look for static Inner classes with code that behaves like a nonstatic (regular inner) class. Be careful to spot them and you’ll be scoring points in the question without any trouble…

Previous Chapter: Chapter 54 - Anonymous Inner Classes

Next Chapter: Quick Recap - Inner classes
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers