Saturday, December 12, 2009

Thread _ Notes

Threads can be created by extending Thread and overriding the
public void run() method.
q Thread objects can also be created by calling the Thread constructor that
takes a Runnable argument. The Runnable object is said to be the target of
the thread.
q You can call start() on a Thread object only once. If start() is called
more than once on a Thread object, it will throw a RuntimeException.
q It is legal to create many Thread objects using the same Runnable object as
the target.
q When a Thread object is created, it does not become a thread of execution
until its start() method is invoked. When a Thread object exists but hasn't
been started, it is in the new state and is not considered alive.
Transitioning Between Thread States (Objective 4.2)
q Once a new thread is started, it will always enter the runnable state.
q The thread scheduler can move a thread back and forth between the
runnable state and the running state.
q For a typical single-processor machine, only one thread can be running at a
time, although many threads may be in the runnable state.
q There is no guarantee that the order in which threads were started
determines the order in which they'll run.
q There's no guarantee that threads will take turns in any fair way. It's up
to the thread scheduler, as determined by the particular virtual machine
implementation. If you want a guarantee that your threads will take turns
regardless of the underlying JVM, you can use the sleep() method. This
prevents one thread from hogging the running process while another thread
starves. (In most cases, though, yield() works well enough to encourage
your threads to play together nicely.)
q A running thread may enter a blocked/waiting state by a wait(), sleep(),
or join() call.
3
q A running thread may enter a blocked/waiting state because it can't acquire
the lock for a synchronized block of code.
q When the sleep or wait is over, or an object's lock becomes available, the
thread can only reenter the runnable state. It will go directly from waiting to
running (well, for all practical purposes anyway).
q A dead thread cannot be started again.
Sleep, Yield, and Join (Objective 4.2)
q Sleeping is used to delay execution for a period of time, and no locks are
released when a thread goes to sleep.
q A sleeping thread is guaranteed to sleep for at least the time specified in
the argument to the sleep() method (unless it's interrupted), but there is
no guarantee as to when the newly awakened thread will actually return to
running.
q The sleep() method is a static method that sleeps the currently executing
thread's state. One thread cannot tell another thread to sleep.
q The setPriority() method is used on Thread objects to give threads
a priority of between 1 (low) and 10 (high), although priorities are not
guaranteed, and not all JVMs recognize 10 distinct priority levels—some
levels may be treated as effectively equal.
q If not explicitly set, a thread's priority will have the same priority as the
priority of the thread that created it.
q The yield() method may cause a running thread to back out if there are
runnable threads of the same priority. There is no guarantee that this will
happen, and there is no guarantee that when the thread backs out there
will be a different thread selected to run. A thread might yield and then
immediately reenter the running state.
q The closest thing to a guarantee is that at any given time, when a thread
is running it will usually not have a lower priority than any thread in the
runnable state. If a low-priority thread is running when a high-priority thread
enters runnable, the JVM will usually preempt the running low-priority
thread and put the high-priority thread in.
q When one thread calls the join() method of another thread, the currently
running thread will wait until the thread it joins with has completed. Think
of the join() method as saying, "Hey thread, I want to join on to the end
of you. Let me know when you're done, so I can enter the runnable state."
Two-Minute Drill 731
732 Chapter 9: Threads
Concurrent Access Problems and Synchronized Threads (Obj. 4.3)
q synchronized methods prevent more than one thread from accessing an
object's critical method code simultaneously.
q You can use the synchronized keyword as a method modifier, or to start a
synchronized block of code.
q To synchronize a block of code (in other words, a scope smaller than the
whole method), you must specify an argument that is the object whose lock
you want to synchronize on.
q While only one thread can be accessing synchronized code of a particular
instance, multiple threads can still access the same object's unsynchronized code.
q When a thread goes to sleep, its locks will be unavailable to other threads.
q static methods can be synchronized, using the lock from the
java.lang.Class instance representing that class.
Communicating with Objects by Waiting and Notifying (Obj. 4.4)
q The wait() method lets a thread say, "there's nothing for me to do now, so
put me in your waiting pool and notify me when something happens that I
care about." Basically, a wait() call means "wait me in your pool," or "add
me to your waiting list."
q The notify() method is used to send a signal to one and only one of the
threads that are waiting in that same object's waiting pool.
q The notify() method can NOT specify which waiting thread to notify.
q The method notifyAll() works in the same way as notify(), only it sends
the signal to all of the threads waiting on the object.
q All three methods—wait(), notify(), and notifyAll()—must be
called from within a synchronized context! A thread invokes wait() or
notify() on a particular object, and the thread must currently hold the lock
on that object.
Deadlocked Threads (Objective 4.4)
q Deadlocking is when thread execution grinds to a halt because the code is
waiting for locks to be removed from objects.
q Deadlocking can occur when a locked object attempts to access another
locked object that is trying to access the first locked object. In other words,
both threads are waiting for each other's locks to be released; therefore, the
locks will never be released!
q Deadlocking is bad. Don't do it.

Tuesday, December 8, 2009

SCJP 5.0 Syllabus

Objectives

Section 1: Declarations, Initialization and Scoping


· Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).
· Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class.
· Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.
· Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.
· Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class.


Section 2: Flow Control


· Develop code that implements an if or switch statement; and identify legal argument types for these statements.
· Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.
· Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.
· Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.
· Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error.
· Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.


Section 3: API Contents


· Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.
· Given a scenario involving navigating file systems, reading from files, or writing to files, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader,BufferedWriter, File, FileReader, FileWriter and PrintWriter.
· Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.
· Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.


Section 4: Concurrency


· Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.
· Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.
· Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.


Section 5: OO Concepts


· Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.
· Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.
· Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.
· Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass or overloaded constructors.
· Develop code that implements "is-a" and/or "has-a" relationships.


Section 6: Collections / Generics


· Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.
· Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.
· Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions.
· Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.
· Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the "natural ordering" of primitive wrapper classes and java.lang.String on sorting.


Section 7: Fundamentals


· Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.
· Given an example of a class and a command-line, determine the expected runtime behavior.
· Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.
· Given a code example, recognize the point at which an object becomes eligible for garbage collection, and determine what is and is not guaranteed by the garbage collection system. Recognize the behaviors of System.gc and finalization.
· Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully.
· Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.

reference : http://java.sun.com/docs/books/tutorial/extra/certification/index.html