Monday, August 25, 2008

SCJP-THREADS

Threads Important Points from Whizlabs:

 If class A extends Thread class and doesn't override the run method, calling new A ().start  No compile and run time errors. Thread class run is called, which does nothing.
 The run method can be overloaded. But the run method with
o public void run () {} is called when the start () is called on the thread.
 Sleep method must be enclosed in try-catch blocks as it throws Interrupted Exception. Same is the case with wait and join methods also. Otherwise it gives compile time error
 MyTherad mt = new MyThread (); mt.run ()  calls run method like any other method. It doesn’t throw compile or runtime errors.
 Every Java Thread is a member of a Thread group.  If you do not specify the group of a thread, it will be a member of the group of the thread that started it, or the member of the current thread’s group. So if you start a thread from main thread without specifying the thread group, this thread will be member of the main thread group.
 A group of threads can’t be assigned a priority applicable for all the threads of that group. In other words there is no setPriority () method in ThreadGroup class. Rather a ThradGroup can be assigned the maximum priority by calling the setMaxPriority () method indicating that no thread of that group can have more priority than the set value of the group.
 A thread group can contain any number of threads.
 You can’t differentiate between a new Thread and a dead thread because calling isAlive() method in both the situations will return false. Method isAlive() returns true if a thread has been started but not yet died i.e. a thread is either runnable, running or non-running state.
 If a Thread is assigned a priority more than Thread.MAX_PRIORITY, it will compile fine but it will throw IllegalArgumentException during runtime.
 If a thread’s priority is set within range of Thread.MIN_PRIORITY and Thread.MAX_PRIORITY but higher than the Thread Group’s Max Priority, it will compile fine but at run time the scheduling system will assign the thread’s priority the is lower of the two priorities.
 Thread may share data between one another
 wait(), suspend(), stop(), sleep()  will definitely stop a thread from executing
 yield(), setPriority(), notify(), notifyAll()  may not stop a running thread
 The yield() method is used to call from the currently running thread to allow another thread of the same or higher priority to run. It is not guaranteed that the Thread that grabs the CPU will be of the higher priority. It will depend on the underlying OS or the threading algorithm of the JVM
 A subclass decides whether an inherited method should be marked synchronized or not. A synchronized method can be inherited to be non-synchronized or vice versa.
 Synchronized methods can call methods which are not synchronized; there is no restriction on it.
 Static methods can be synchronized; in this case the lock is obtained on the Class object of the class.
 Directly sub classing Thread class does NOT give access to more functionality than using the Runnable interface
 It is very important to remember that synchronized modifier can NOT be applied to constructor; else it will give compiler error. However block synchronization can be used within the constructors.
 MyThread implements Runnable; if Mythread doesn’t implement the run method correctly, it will give compile error.
 Thread type (Daemon thread / User Thread) can be changed by calling setDaemon(boolean), as many times you wish BUT only before the thread has been started. Attempt to change the thread type after start(), will compile fine but will throw IllegalThreadStateException when run, which is an indirect subclass of RuntimeException.
 Thread name doesn’t need to be unique, so two threads with the same name can execute separately.
 public class Thread extends Object implements Runnable
 A thread is a thread of execution in a program.
 The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
 Every thread has a priority.
 Threads with higher priority are executed in preference to threads with lower priority.
 Each thread may or may not also be marked as a daemon.
 When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.
 When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class).
 The Java Virtual Machine continues to execute threads until either of the following occurs:
o The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
o All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
 Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.

public interface Runnable:
 The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
 The class must define a method of no arguments called run.
 This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread.
 Being active simply means that a thread has been started and has not yet been stopped.
 In addition, Runnable provides the means for a class to be active while not subclassing Thread.
 A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target.
 In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.
Method Description
public void run() When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread
The general contract of the method run is that it may take any action whatsoever.

Methods of Thread Class:
Method Signature Description
public static Thread currentThread() Returns a reference to the currently executing thread object.
public static void yield() Causes the currently executing thread object to temporarily pause and allow other threads to execute.
public static void sleep(long millis) throws InterruptedException Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.
InterruptedException - if another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
public static void sleep(long millis, int nanos) throws InterruptedException Causes the currently executing thread to sleep (cease execution) for the specified number of milliseconds plus the specified number of nanoseconds. The thread does not lose ownership of any monitors.
IllegalArgumentException - if the value of millis is negative or the value of nanos is not in the range 0-999999.
public void start() Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
IllegalThreadStateException - if the thread was already started.
public void run() If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
Subclasses of Thread should override this method.
public final void stop() Forces the thread to stop executing.
It is permitted to stop a thread that has not yet been started. If the thread is eventually started, it immediately terminates.
public void interrupt() Interrupts this thread.
First the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
public static boolean interrupted() Tests whether the current thread has been interrupted. The interrupted status of the thread is cleared by this method. In other words, if this method were to be called twice in succession, the second call would return false (unless the current thread were interrupted again, after the first call had cleared its interrupted status and before the second call had examined it).
Returns: true if the current thread has been interrupted; false otherwise.
public boolean isInterrupted() Tests whether this thread has been interrupted. The interrupted status of the thread is unaffected by this method.
Returns: true if this thread has been interrupted; false otherwise.
public void destroy() Destroys this thread, without any cleanup. Any monitors it has locked remain locked. (This method is not implemented.)
public final boolean isAlive() Tests if this thread is alive. A thread is alive if it has been started and has not yet died.
public final void setPriority(int newPriority) Changes the priority of this thread.
First the checkAccess method of this thread is called with no arguments. This may result in throwing a SecurityException.
Otherwise, the priority of this thread is set to the smaller of the specified newPriority and the maximum permitted priority of the thread's thread group.
Throws: IllegalArgumentException - If the priority is not in the range MIN_PRIORITY to MAX_PRIORITY.
SecurityException - if the current thread cannot modify this thread.
public final int getPriority() Returns this thread's priority.
public final void setName(String name) Changes the name of this thread to be equal to the argument name.
public final String getName() Returns this thread's name.
public final ThreadGroup getThreadGroup() Returns the thread group to which this thread belongs. This method returns null if this thread has died (been stopped).
public static int activeCount() Returns the number of active threads in the current thread's thread group.
public int countStackFrames() Deprecated
public final void join(long millis) throws InterruptedException Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
public final void join(long millis, int nanos) throws InterruptedException Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.
IllegalArgumentException - if the value of millis is negative the value of nanos is not in the range 0-999999.
public final void join() throws InterruptedException Waits for this thread to die.
public static void dumpStack() Prints a stack trace of the current thread. This method is used only for debugging.
public final void setDaemon(boolean on) Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.
This method must be called before the thread is started.
This method first calls the checkAccess method of this thread with no arguments. This may result in throwing a SecurityException (in the current thread).
Parameters:
on - if true, marks this thread as a daemon thread.
Throws: IllegalThreadStateException - if this thread is active.

public final boolean isDaemon() Tests if this thread is a daemon thread.
public final void checkAccess() Determines if the currently running thread has permission to modify this thread.
public String toString() Returns a string representation of this thread, including the thread's name, priority, and thread group.
public static boolean holdsLock(Object obj) Returns true if and only if the current thread holds the monitor lock on the specified object.
This method is designed to allow a program to assert that the current thread already holds a specified lock: assert Thread.holdsLock(obj);
NullPointerException - if obj is null


Kai’s Notes:

(1) Stop a thread

Know what methods you can call to interrupt or suspend a thread.
Know which classes these methods reside in and whether they are staticor not.

* yield() and sleep() of Thread class are static.
* start(), run() and interrupt() of Thread class are non-static.
* wait(), notify() and notifyAll() of Object class are non-static.

When will the execution of a Thread eventually stop?
x a) In case another Thread with higher priority thread enters the runnable state.
x b) Through a call to suspend()
x c) Through a call to wait()
x d) Through a call to MediaTracker.waitforID()
e) If the current thread starts another thread.
I think the answer are a,b,c if you considering that stop means coming
back to ready state. What about choice d.

Reply#1: Choice d is also correct, because you can use MediaTracker to load one or more images and to wait until those images have been completely loaded and are ready to be used. So when waitForID() is called, the execution of the thread stops until all the images have been loaded. This is correct because I got this question in the exam, and I got 100% in threads.

Reply #2: One of the cloudy issues that I did not like about the test was the ambiguity of the word 'stop' on the test: do they mean entering the stop state or do they mean 'the thread ceases to execute, but can run in the future'. This question and the test will refer to the latter definition. Therefore:
(a) wrong, because of pre-emptive and time sharing OS differences.
(b) true, suspend() puts you in the blocked state so answer is true, BUT suspend is deprecated in java 1.2 so this should not be given as an alternative.
(c) true, wait() causes the thread execution to stop and enter the runnable queue for its time out period or being notified and obtaining a lock.
(d) false, MediaTracker works to keep track of image loading so the current thread can keep on doing whatever it does.
(e) false, how does a current thread start another thread? Yield() will cease the execution of the current thread to give another thread in the runnable queue a chance to run, and start() will put a newly created thread into the runnable queue, but nothing other than the OS can force
a thread to run.

Reply #3: These are the answers based on both the assumptions.
Assumption 1: Stop means the thread cannot be run again. In this case,
none of the answers are correct. Assumption 2: Stop means temporary
suspension of thread. In this case, a,b,c,d are correct.
a is correct, because the policy is governed by the underlying OS.
b is correct, coz u can call a suspend method to stop the thread temporarily.
c is correct, coz the thread releases the monitor and waits for another thread to issue a notify.(refer to JDK docs or API)
d is correct, coz the current thread waits until the mediatracker's done with its work.
e is false, coz starting another thread does not stop the currentthread.

Which methods or cases may cause a thread to stop executing:

x wait()

x sleep()

x suspend()

x stop()

x MediaTracker.waitForID() // Something about loading a graphic
image of MediaTracker class

x Interrupted()

x The program exits via a call to exit(0)

- If the current thread starts a new thread.

x In case another thread with higher priority enters the
runnable state.

Are we supposed to pick stop() and suspend(), because they are
deprecated? I didn't know about this question, but interrupting can't
stop a thread, it can only wake up sleeping or waiting thread.


Jyoti's notes: Conditions that might prevent a thread from executing :


x The thread is not the highest priority thread and so cannot get CPU time.

x The thread is waiting on a condition because someone invoked wait() for the thread.

x The thread has explicitly yielded control by invoking yield() to allow another thread of the same priority to run.

x The thread has been put to sleep using the sleep() method

x Someone has suspended the thread using the suspend() method. (deprecated in Java 2)

x It is blocked for file I/O

x There is more than one thread with the same highest priority and JVM is switching between these threads, at the moment, the thread in question is awaiting CPU time.

Does MediaTracker.waitForID() block the current thread?

Ans: If it didn't block the current thread, it could not do its job, right? :-) The objective is to WAIT UNTIL something happens. Of course, it doesn't stop the separate thread generated by the AWT to load the image. Or any other thread but its own. Also, the requirement that it be used in a "try/catch (InterruptedException e)" block suggests the same.

(2) Theory
The thread questions were tenuous and some took the same form as the garbage collection questions.

Threads is more theoretical.

Which is true about Threads:
A. If suspended, cannot be restarted.
B. Stop running, if another Thread with higher priority is getting runnable.
C. Stop running, if the Thread starts another Thread.
D. If dead, cannot be restarted.
E. If interrupted, stop running.
F. .. I cannot remember. :(

I choose B,D,E. (a classic question, but I had 2-3 question about threads in this style)

Is it true or false, i would appreciate the answer?

A) Java Interpreter exits normally after the non-daemon threads have stopped. (True?)

B) Current thread suspends, when a file is opened for reading. (True?)

a) A thread can stop execution, if it was performing an I/O task with a remote file. (True?)

b) It is possible to suspend a thread indefinitely. (?)

c) Only way to make a thread is to extend the Thread class. (False)

d) After the thread exit main(), it can still run. (related to garbage collection) (?)

When, exactly, does a Java application/applet stop execution?
Does it stop execution when there are no more Daemon threads running?
What is a Daemon thread? Does it stop execution when there are no more User threads?


It keeps running until all user threads have ended. Here is the definition of daemon thread from Bruce Eckels TIJ. A "daemon" thread is one that is supposed to provide a general service in the background as long as the program is running, but is not part of the essence of the program. Thus, when all of the non-daemon threads complete the program is terminated.

What's daemon or non-daemon threads?

Daemon threads are utility threads to service regular non-daemon threads. In Java, their only reason of being is "service to others". If ONLY daemon threads are left in a JVM, the program exits. I guess an implication would be that if you create some daemon threads in your program, you don't have to worry about killing them since they will die when the 'real' threads are through executing.... Any good book and/or chapter and/or on-line tutorial on Java threads should cover this.

(3) When to use "synchronize" keyword

What modifier to use, if a method needs to protect the lock of its object.

A. public
B. protected
C. private
D. final
E. synchronized

Threads, there were couple of questions on synchronized.

Synchronization was asked.

Which modifier can be used together with 'synchronized'?

(4) Implement Runnable and start a thread

Post from Maha Anna:

A thread stops permanently becoz of
1. finishes it 's run method --YES
2. interrupt is invoked --- NO
3. stop --is invoked but since it is –YES deprecated it is no longer in use. should we use if given in exam
Thread stops executing for a while becoz of
1. sleep -YES
2. I/O Operations YES
3. wait --YES
4. yield --YES
5. suspend --deprecated??? should we use if given in exam --YES
6. higher priority thread enters --YES
7. if a thread creates a new thread. --NO
When an Intertrupt is invoked, the waiting, blocked or sleeping threads moves to "ready" state and then throws interrupted exception
I think for both 6 and 7 the answer is maybe. Anytime other threads are present, this may cause the current thread to stop executing temporarily, but there are no guarantees. If another thread is higher priority than the current thread, it's more likely that the current thread will pause, but still no guarantees.
For the options
6. higher priority thread enters --YES
7. if a thread creates a new thread. --NO
I also thought like you. But from the Exam point of view (only yes or no, if at all they word the answers like this ) what shoud we do? We shd think of the closest YES/NO .So a Higher priority thread enters (I assume the Ready state) means it most likely going to enter into Running state than NOT. So I thought the answer is YES. If a thread creates a new thread means the new thread is going to have the SAME PRIORITY as the creating thread, in which case it has less chance to enter into a Running state ,unless the creater yield() than as in option 6. So I inclained towards NO.
That makes sense, and I agree. I just didn't want people to think those answers were absolute. Yeah, if you get an ambiguous question like that on the actual test (which I don't think is nearly as common as ambiguous sample questions are) then you must simply make your best guess.

The isAlive Method
 The isAlive method returns true if the thread has been started and not stopped.
 If the isAlive method returns false, you know that the thread either is a New Thread or is Dead.
 If the isAlive method returns true, you know that the thread is either Runnable or Not Runnable.
 Runnable State includes Ready and Running States.
 You cannot differentiate between a New Thread or a Dead thread. Nor can you differentiate between a Runnable thread and a Not Runnable thread.
Understanding Thread Priority
 When a Java thread is created, it inherits its priority from the thread that created it.
 You can also modify a thread's priority at any time after its creation using the setPriority method.
 Thread priorities are integers ranging between MIN_PRIORITY and MAX_PRIORITY (constants defined in the Thread class).
 The higher the integer, the higher the priority.
 At any given time, when multiple threads are ready to be executed, the runtime system chooses the runnable thread with the highest priority for execution.
 Only when that thread stops, yields, or becomes not runnable for some reason will a lower priority thread start executing.
 If two threads of the same priority are waiting for the CPU, the scheduler chooses one of them to run in a round-robin fashion. The chosen thread will run until one of the following conditions is true:
• A higher priority thread becomes runnable.
• It yields, or its run method exits.
• On systems that support time-slicing, its time allotment has expired.
Then the second thread is given a chance to run, and so on, until the interpreter exits.
 The Java runtime system's thread scheduling algorithm is also preemptive. If at any time a thread with a higher priority than all other runnable threads becomes runnable, the runtime system chooses the new higher priority thread for execution. The new higher priority thread is said to preempt the other threads.
 Rule of thumb: At any given time, the highest priority thread is running. However, this is not guaranteed. The thread scheduler may choose to run a lower priority thread to avoid starvation. For this reason, use priority only to affect scheduling policy for efficiency purposes. Do not rely on thread priority for algorithm correctness
Grouping Threads
 Every Java thread is a member of a thread group.
 Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually.
 For example, you can start or suspend all the threads within a group with a single method call.
 Java thread groups are implemented by the ThreadGroup class in the java.lang package.
 The runtime system puts a thread into a thread group during thread construction.
 When you create a thread, you can either allow the runtime system to put the new thread in some reasonable default group or you can explicitly set the new thread's group.
 The thread is a permanent member of whatever thread group it joins upon its creation--you cannot move a thread to a new group after the thread has been created.

The Default Thread Group
 If you create a new Thread without specifying its group in the constructor, the runtime system automatically places the new thread in the same group as the thread that created it (known as the current thread group and the current thread, respectively).
 When a Java application first starts up, the Java runtime system creates a ThreadGroup named main. Unless specified otherwise, all new threads that you create become members of the main thread group. :
 If you create a thread within an applet, the new thread's group may be something other than main, depending on the browser or viewer that the applet is running in

Methods that Operate on All Threads within a Group
 The ThreadGroup class has three methods that allow you to modify the current state of all the threads within that group:
• resume
• stop
• suspend
 These methods apply the appropriate state change to every thread in the thread group and its subgroups.

Making a Thread Not Runnable
A thread becomes Not Runnable when one of these events occurs:
• Its sleep method is invoked.
• The thread calls the wait method to wait for a specific condition to be satisifed.
• The thread is blocking on I/O.
One Question:
Most of the test questions were easy, but there were some tough thread questions. For example, I had a question that was almost identical to this:
Thread b holds the lock to object a. Thread c is blocked inside a wait call on object a. What will allow c to continue running?
 Threads do not have parent-child relationships
Q8. Select most appropriate answer for the following code
class MyThread extends Thread
{
public void run()
{
try {
Thread.sleep(300);
}
catch (InterruptedException e)
{
System.err.println(e);
}

System.out.println("I am alive");
}
}
public class MyClass
{
public static void main(String args[])
{
new MyThread().start();

int arr[] = new int[20];

arr[20] = 1237;
}
}

Thread MyThread continues even after runtime exception is thrown in
main() and prints "I am alive"
Thread MyThread dies as soon as runtime exception is thrown in main() without printing "I am alive"
Will print "I am alive" without any runtime error
Will give compilation error
SKIP THE QUESTION
Thread MyThread continues even after runtime exception is thrown inThread MyThread continues even after runtime exception is thrown in main() and prints "I am alive" Correct

No comments: