Thursday, October 13, 2011

Django web development

You can find me now blogging at Agiliq.com where I blog about Django Web Development.

Saturday, April 01, 2006

Declarations and Access Control


Write code that declares, constructs and initializes arrays of any base type using any of the permitted forms both for declaration and for initialization.

Declaring arrays:

For example,use either

 int[] x;

or

 int x[];

Both are legal positions for the brackets. To declare a multidimensional array, use multiple sets of brackets, e.g. int i[][]; declares a two dimensional array. Note that, for example, int[]i[]; is also legal, and means the same thing. In Java, multidimensional arrays can be "not square" i.e. they are just arrays of arrays, and each of those constituent arrays can be of a different size.

Construct arrays:

Arrays are objects. Use the new keyword to construct them. For example having declared an array i:

int[] i;

you then construct the array and assign it to i as follows:

i = new int[10];

The size of the array is in the brackets (in this example 10). It is common to do both operations in one statement:

int i[] = new int[10];

To initialize an array using loop iteration:

An example:

 int array[] = new int[15];
 for(int j=0; j

Write code to initialize an array using the combined declaration and initialization format:

An example:

char c[]= new char[] {'a','b','c','d','e'};

or you can use

char c[]= {'a','b','c','d','e'};
Declare classes, nested classes, methods, instance variables, static variables and automatic (method local) variables making appropriate use of all permitted modifiers (such as public, final, static, abstract etc.). State the significance of each of these modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.

This is fundamental Java. If you are unsure of this topic, see a textbook.

A good but technical reference for these kinds of issues is the Java Language Specification (not for beginners). It is available at the following URL: http://java.sun.com/docs/books/jls/html/index.html

Some terms and their synonyms:

Scope/Visibility: Where something can be seen / is accessable from.

Nested/Inner Class: A class whose code sits inside the body of another 'outer' class. It exists 'inside' the class in that it can see the private methods and variables.

Instance/Member: Means the method/variable/nested class belongs to each object which is an instance of the class. The term 'a member' is often used to refer to both methods and variables of this type. Cannot be accessed by statically i.e. without having an instance of the class.

Class/Static: The method/variable/nested class belongs to the class as opposed to the instances of the class. Can be used without creating an instance of the class, but static methods/nested class cannot use instancts variables/methods.

Local/Automatic variable: A variable which is declared within a method or as a parameter to the method. Cannot be seen outside the method.

Scoping Types

"default" or "friendly" - this is where no modifier is used. Means something is only visible to classes in the same package.

protected - can only be accessed by classes in the same package or subclasses of this class. This frequently surprises experienced developers, especially those with a prior backround in the mutant hybrid of object orientated programming and assembly language known as 'C++' :-) To fair the name is misleading, as it sounds like it restricts access, where as it in fact it adds subclasses outside the package to the list of things that can access the item in question, as compared to using "default" access.

public - can be accessed by any other class.

private - can only be accessed from inside the class.

Declare classes using the modifiers public, abstract or final:

public - is visible outside of its package. Without this modifier, the class cannot be accessed outside its package.

abstract - cannot be instantiated, is allowed to contain abstract methods.

final - cannot be subsclassed.

Using the modifiers private, protected, public, static, final, native or abstract:

private - can only be accessed from inside the class. Private members are not inherited by subclasses. Inner classes can be declared private.

protected - can only be accessed by classes in the same package or subclasses of this class.

public - can be accessed by any other class.

static - belongs to the class rather than any particular instance of the class. For variables, effectively, there is just one copy of this variable for all instances of the class, and if an instance changes the value, the other instances see that new value. For methods, it means the method can be called without having created an instance, but within the methodd you cannot use the this keyword, or refer to instance variables and methods directly (without creating an instance and referring to the variable/class in that instance). For inner classes, it means they can be instantiated without having an instance of the enclosing class, but as with static methods, the methods of the inner class cannot refer to instance variables or methods of the enclosing class directly.

final - cannot be changed. Variables are constants, methods cannot be overridden, classes cannot be subclassed. Since Java1.1 you can declare the variable without assigning a value. Once you assign a value, you cannot change it. The are known as 'blank' finals, are frequently used for things like constants you wish to initialise from a configuration file.

native - a method which is not written in java and is outside the JVM in a library.

abstract - a method which is not implemented. Must be implemented in a subclass if that subclass is to be 'concrete' and allow people to instantiate it.

Nested Classes

To define a non-static nested class either in a class or method scope:

Place the class definition (for the nested class) inside another class definition (the outer class) or a method.

To define, in method scope, an anonymous nested class that implements a specified interface:

An anonymous nested class is defined where is it instantiated (in a method). An anonymous nested class must either implement an interface or extend a class, but the implements or extends keywords are not used. For example the following line causes the method to return an object which is an instance of an anonymous nested class:

return new SomeClass() { /*body of the anonymous class goes here*/ };

You might like to think of an anonymous nested class as part of a really long new statement, which happens to contain a class definition, and which is why it has a ";" at the end. The following example calls someMethod(), passing an instance of the anonymous nested class:

someMethod(new SomeClass() { /*body of the anonymous class goes here*/ });

In both cases SomeClass() is not the name of the anonymous class (anonymous means it has no name) rather is it the name of the class that you are extending or the interface you are implementing. These classes cannot define a constructor, as they do not have a name that you can use to declare the constructor method. If SomeClass() is a class, the default constructor of that class is called, if you want to use a non-default constructor instead, you supply arguments e.g.:

return new SomeClass(12) { /*body of the anonymous class goes here*/ };

will call the SomeClass constructor which takes an int.

Write code in a non-static method of the outer class to construct an instance of the nested class.

Inner x = new Inner(); constructs an instance of Inner where Inner is a nested class defined in the current class.

Write code to construct an instance on a nested class where either no this object exists, or the current this object is not an instance of the outer class.

You must create an instance of the outer class first. Given a class, Outer, containing a nested class Inner:
Outer.Inner y = new Outer().new Inner();

The above creates an instance of Inner called y, but it had to construct an instance of Outer first. The following example creates the Outer instance on a separate line, the syntax in the second line is the one you use when you already have an instance of the outer class.

Outer x = new Outer();
Outer.Inner y = x.new Inner();
If Inner is static, you can use:
Outer.Inner I= new Outer.Inner();

State which variables and methods in enclosing scopes are accessible from methods of the inner class.

A non-static inner class has access to all member variables and methods of the containing class. If the inner class is defined inside a method, it has access to those method (a.k.a. automatic or local) variables which are declared final, in addition to the above.

A static inner class is restricted in the same way as a static method: it cannot refer to instance variables and methods of the containing class directly (without creating an instance and referring to the variable/class in that instance).

For a given class, determine if a default constructor will be created and if so state the prototype of that constructor.

The default constructor takes no arguments e.g. classname() where classname is the name of you class. A default constructor is automatically created only if you do not create any constructors in your class. If you create a non-default constructor (i.e. one that takes an argument), then you may have to create a default one yourself, if you want there to be one.

All constructors call the default constructor of its parents class (if there is one), and so on up the hierarchy to Object, unless you specify a different constructor using super(...) (to use a constructor in the parent) or this(...). If you use such calls, they must be the first thing in the constructor.


©1999, 2000, 2002 Dylan Walsh. Under free documentation liscence.

Saturday, February 18, 2006

This link is to get listed in a directory.

Human-Anatomy.net Software

Wednesday, December 28, 2005

Written by Dylan Walsh. Released under FDL.

Declarations and Access Control

Write code that declares, constructs and initializes arrays of any base type using any of the permitted forms both for declaration and for initialization.

Declaring arrays:

For example,use either

 int[] x;

or

 int x[];

Both are legal positions for the brackets. To declare a multidimensional array, use multiple sets of brackets, e.g. int i[][]; declares a two dimensional array. Note that, for example, int[]i[]; is also legal, and means the same thing. In Java, multidimensional arrays can be "not square" i.e. they are just arrays of arrays, and each of those constituent arrays can be of a different size.

Construct arrays:

Arrays are objects. Use the new keyword to construct them. For example having declared an array i:

int[] i;

you then construct the array and assign it to i as follows:

i = new int[10];

The size of the array is in the brackets (in this example 10). It is common to do both operations in one statement:

int i[] = new int[10];

To initialize an array using loop iteration:

An example:

 int array[] = new int[15];
 for(int j=0; j  

Write code to initialize an array using the combined declaration and initialization format:

An example:

char c[]= new char[] {'a','b','c','d','e'};

or you can use

char c[]= {'a','b','c','d','e'};
Declare classes, nested classes, methods, instance variables, static variables and automatic (method local) variables making appropriate use of all permitted modifiers (such as public, final, static, abstract etc.). State the significance of each of these modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.

This is fundamental Java. If you are unsure of this topic, see a textbook.

A good but technical reference for these kinds of issues is the Java Language Specification (not for beginners). It is available at the following URL: http://java.sun.com/docs/books/jls/html/index.html

Some terms and their synonyms:

Scope/Visibility: Where something can be seen / is accessable from.

Nested/Inner Class: A class whose code sits inside the body of another 'outer' class. It exists 'inside' the class in that it can see the private methods and variables.

Instance/Member: Means the method/variable/nested class belongs to each object which is an instance of the class. The term 'a member' is often used to refer to both methods and variables of this type. Cannot be accessed by statically i.e. without having an instance of the class.

Class/Static: The method/variable/nested class belongs to the class as opposed to the instances of the class. Can be used without creating an instance of the class, but static methods/nested class cannot use instancts variables/methods.

Local/Automatic variable: A variable which is declared within a method or as a parameter to the method. Cannot be seen outside the method.

Scoping Types

"default" or "friendly" - this is where no modifier is used. Means something is only visible to classes in the same package.

protected - can only be accessed by classes in the same package or subclasses of this class. This frequently surprises experienced developers, especially those with a prior backround in the mutant hybrid of object orientated programming and assembly language known as 'C++' :-) To fair the name is misleading, as it sounds like it restricts access, where as it in fact it adds subclasses outside the package to the list of things that can access the item in question, as compared to using "default" access.

public - can be accessed by any other class.

private - can only be accessed from inside the class.

Declare classes using the modifiers public, abstract or final:

public - is visible outside of its package. Without this modifier, the class cannot be accessed outside its package.

abstract - cannot be instantiated, is allowed to contain abstract methods.

final - cannot be subsclassed.

Using the modifiers private, protected, public, static, final, native or abstract:

private - can only be accessed from inside the class. Private members are not inherited by subclasses. Inner classes can be declared private.

protected - can only be accessed by classes in the same package or subclasses of this class.

public - can be accessed by any other class.

static - belongs to the class rather than any particular instance of the class. For variables, effectively, there is just one copy of this variable for all instances of the class, and if an instance changes the value, the other instances see that new value. For methods, it means the method can be called without having created an instance, but within the methodd you cannot use the this keyword, or refer to instance variables and methods directly (without creating an instance and referring to the variable/class in that instance). For inner classes, it means they can be instantiated without having an instance of the enclosing class, but as with static methods, the methods of the inner class cannot refer to instance variables or methods of the enclosing class directly.

final - cannot be changed. Variables are constants, methods cannot be overridden, classes cannot be subclassed. Since Java1.1 you can declare the variable without assigning a value. Once you assign a value, you cannot change it. The are known as 'blank' finals, are frequently used for things like constants you wish to initialise from a configuration file.

native - a method which is not written in java and is outside the JVM in a library.

abstract - a method which is not implemented. Must be implemented in a subclass if that subclass is to be 'concrete' and allow people to instantiate it.

Nested Classes

To define a non-static nested class either in a class or method scope:

Place the class definition (for the nested class) inside another class definition (the outer class) or a method.

To define, in method scope, an anonymous nested class that implements a specified interface:

An anonymous nested class is defined where is it instantiated (in a method). An anonymous nested class must either implement an interface or extend a class, but the implements or extends keywords are not used. For example the following line causes the method to return an object which is an instance of an anonymous nested class:

return new SomeClass() { /*body of the anonymous class goes here*/ };

You might like to think of an anonymous nested class as part of a really long new statement, which happens to contain a class definition, and which is why it has a ";" at the end. The following example calls someMethod(), passing an instance of the anonymous nested class:

someMethod(new SomeClass() { /*body of the anonymous class goes here*/ });

In both cases SomeClass() is not the name of the anonymous class (anonymous means it has no name) rather is it the name of the class that you are extending or the interface you are implementing. These classes cannot define a constructor, as they do not have a name that you can use to declare the constructor method. If SomeClass() is a class, the default constructor of that class is called, if you want to use a non-default constructor instead, you supply arguments e.g.:

return new SomeClass(12) { /*body of the anonymous class goes here*/ };

will call the SomeClass constructor which takes an int.

Write code in a non-static method of the outer class to construct an instance of the nested class.

Inner x = new Inner(); constructs an instance of Inner where Inner is a nested class defined in the current class.

Write code to construct an instance on a nested class where either no this object exists, or the current this object is not an instance of the outer class.

You must create an instance of the outer class first. Given a class, Outer, containing a nested class Inner:
Outer.Inner y = new Outer().new Inner();

The above creates an instance of Inner called y, but it had to construct an instance of Outer first. The following example creates the Outer instance on a separate line, the syntax in the second line is the one you use when you already have an instance of the outer class.

Outer x = new Outer();
Outer.Inner y = x.new Inner();
If Inner is static, you can use:
Outer.Inner I= new Outer.Inner();

State which variables and methods in enclosing scopes are accessible from methods of the inner class.

A non-static inner class has access to all member variables and methods of the containing class. If the inner class is defined inside a method, it has access to those method (a.k.a. automatic or local) variables which are declared final, in addition to the above.

A static inner class is restricted in the same way as a static method: it cannot refer to instance variables and methods of the containing class directly (without creating an instance and referring to the variable/class in that instance).

For a given class, determine if a default constructor will be created and if so state the prototype of that constructor.

The default constructor takes no arguments e.g. classname() where classname is the name of you class. A default constructor is automatically created only if you do not create any constructors in your class. If you create a non-default constructor (i.e. one that takes an argument), then you may have to create a default one yourself, if you want there to be one.

All constructors call the default constructor of its parents class (if there is one), and so on up the hierarchy to Object, unless you specify a different constructor using super(...) (to use a constructor in the parent) or this(...). If you use such calls, they must be the first thing in the constructor.

Tuesday, October 25, 2005

Should I use an Ide while learning java.

Hmmmmmm. IDE's making coding really easy. And they save a lot of time. So If you are a serious Java developer coding without an IDE is realy foolish. But if you are trying to learn Java, and SCJP is an entry level certification, then dont even think about using an advanced IDE like Eclipse. In fact, I gave my SCJP exam after I had learnt a lot of Java and was using Eclipse for some time. I really had forgotten how to use the basic features, the features you are tested on in SCJP. So I had to leave using Eclipse for sometime. But a basic IDE with syntax highlighting, code explorer but certainly without code completion is ok. I would personaly recommend JCreator Lite. I did use it when I was beginning to use java.

This site has some extremely good java resources. And it is completely free.

Wednesday, August 31, 2005

SCJP study notes:Chapter 8 java.lang package

Originally written by Velmurugan Periasamy. Copyright belongs to him.

Chapter 8 java.lang package

· Object class is the ultimate ancestor of all classes. If there is no extends clause, compiler inserts ‘extends object’. The following methods are defined in Object class. All methods are public, if not specified otherwise.

Method

Description

boolean equals(Object o)

just does a == comparison, override in descendents to provide meaningful comparison

final native void wait()

final native void notify()

final native void notifyAll()

Thread control. Two other versions of wait() accept timeout parameters and may throw InterruptedException.

native int hashcode()

Returns a hash code value for the object.

If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.

protected Object clone() throws CloneNotSupportedException

CloneNotSupportedException is a checked Exception

Creates a new object of the same class as this object. It then initializes each of the new object's fields by assigning it the same value as the corresponding field in this object. No constructor is called.

The clone method of class Object will only clone an object whose class indicates that it is willing for its instances to be cloned. A class indicates that its instances can be cloned by declaring that it implements the Cloneable interface. Also the method has to be made public to be called from outside the class.

Arrays have a public clone method.

int ia[ ][ ] = { { 1 , 2}, null };

int ja[ ][ ] = (int[ ] [ ])ia.clone();

A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared, so ia and ja are different but ia[0] and ja[0] are same.

final native Class getClass()

Returns the runtime class of an object.

String toString

Returns the string representation of the object. Method in Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. Override to provide useful information.

protected void finalize() throws

Throwable

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.

The finalize method in Object does nothing. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

· Math class is final, cannot be sub-classed.

· Math constructor is private, cannot be instantiated.

· All constants and methods are public and static, just access using class name.

· Two constants PI and E are specified.

· Methods that implement Trigonometry functions are native.

· All Math trig functions take angle input in radians.

Angle degrees * PI / 180 = Angle radians

· Order of floating/double values:

-Infinity --> Negative Numbers/Fractions --> -0.0 --> +0.0 --> Positive Numbers/Fractions --> Infinity

· abs – int, long, float, double versions available

· floor – greatest integer smaller than this number (look below towards the floor)

· ceil – smallest integer greater than this number (look above towards the ceiling)

· For floor and ceil functions, if the argument is NaN or infinity or positive zero or negative zero or already a value equal to a mathematical integer, the result is the same as the argument.

· For ceil, if the argument is less than zero but greater than –1.0, then the result is a negative zero

· random – returns a double between 0.0(including) and 1.0(excluding)

· round returns a long for double, returns an int for float. (closest int or long value to the argument)

The result is rounded to an integer by adding ½ , taking the floor of the result, and casting the result to type int / long.

(int)Math.floor(a + 0.5f)

(long)Math.floor(a + 0.5d)

· double rint(double) returns closest double equivalent to a mathematical integer. If two values are equal, it returns the even integer value. rint(2.7) is 3, rint(2.5) is 2.

· Math.min(-0.0, +0.0) returns –0.0, Math.max(-0.0, +0.0) returns 0.0, -0.0 == +0.0 returns true.

· For a NaN or a negative argument, sqrt returns a NaN.

· Every primitive type has a wrapper class (some names are different – Integer, Boolean, Character)

· Wrapper class objects are immutable.

· All Wrapper classes are final.

· All wrapper classes, except Character, have a constructor accepting string. A Boolean object, created by passing a string, will have a value of false for any input other than “true” (case doesn’t matter).

· Numeric wrapper constructors will throw a NumberFormatException, if the passed string is not a valid number. (empty strings and null strings also throw this exception)

· equals also tests the class of the object, so even if an Integer object and a Long object are having the same value, equals will return false.

· NaN’s can be tested successfully with equals method.

Float f1 = new Float(Float.NaN);

Float f2 = new Float(Float.NaN);

System.out.println( ""+ (f1 == f2)+" "+f1.equals(f2)+ " "+(Float.NaN == Float.NaN) );

The above code will print false true false.

· Numeric wrappers have 6 methods to return the numeric value – intValue(), longValue(), etc.

· valueOf method parses an input string (optionally accepts a radix in case of int and long) and returns a new instance of wrapper class, on which it was invoked. It’s a static method. For empty/invalid/null strings it throws a NumberFormatException. For null strings valueOf in Float and Double classes throw NullPointerException.

· parseInt and parseLong return primitive int and long values respectively, parsing a string (optionally a radix). Throw a NumberFormatException for invalid/empty/null strings.

· Numeric wrappers have overloaded toString methods, which accept corresponding primitive values (also a radix in case of int,long) and return a string.

· Void class represents void primitive type. It’s not instantiable. Just a placeholder class.

· Strings are immutable.

· They can be created from a literal, a byte array, a char array or a string buffer.

· Literals are taken from pool (for optimization), so == will return true, if two strings are pointing to the same literal.

· Anonymous String objects (literals) may have been optimized even across classes.

· A String created by new operator is always a different new object, even if it’s created from a literal.

· But a String can specify that its contents should be placed in a pool of unique strings for possible reuse, by calling intern() method. In programs that do a lot of String comparisons, ensuring that all Strings are in the pool, allows to use == comparison rather than the equals() method, which is slower.

· All string operations (concat, trim, replace, substring etc) construct and return new strings.

· toUpperCase and toLowerCase will return the same string if no case conversion was needed.

· equals takes an object (String class also has a version of equals that accepts a String), equalsIgnoreCase takes a string.

· Passing null to indexOf or lastIndexOf will throw NullPointerException, passing empty string returns 0, passing a string that’s not in the target string returns –1.

· trim method removes all leading and trailing white-space from a String and returns a new String. White-space means, all characters with value less than or equal to the space character – ‘\u0020’.

· String class is final.

· + and += operators are overloaded for Strings.

· reverse, append, insert are not String methods.

· String Buffers are mutable strings.

· StringBuffer is a final class.

· They can be created empty, from a string or with a capacity. An empty StringBuffer is created with 16-character capacity. A StringBuffer created from a String has the capacity of the length of String + 16. StringBuffers created with the specified capacity has the exact capacity specified. Since they can grow dynamically in size without bounds, capacity doesn’t have much effect.

· append, insert, setCharAt, reverse are used to manipulate the string buffer.

· setLength changes the length, if the current content is larger than specified length, it’s truncated. If it is smaller than the specified length, nulls are padded. This method doesn’t affect the capacity.

· equals on StringBuffer does a shallow comparison. (same like ==) Will return true only if the objects are same. Don’t use it to test content equality

· trim is not a StringBuffer method.

· There is no relationship between String and StringBuffer. Both extend Object class.

· String context means, ‘+’ operator appearing with one String operand. String concatenation cannot be applied to StringBuffers.

· A new String buffer is created.

· All operands are appended (by calling toString method, if needed)

· Finally a string is returned by calling toString on the String Buffer.

· String concatenation process will add a string with the value of “null”, if an object reference is null and that object is appearing in a concatenation expression by itself. But if we try to access its members or methods, a NullPointerException is thrown. The same is true for arrays, array name is replaced with null, but trying to index it when it’s null throws a NullPointerException.

SCJP study notes: Chapter 7 Threads

Originally written by Velmurugan Periasamy. Copyright belongs to him.

Chapter 7 Threads

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

· Java is fundamentally multi-threaded.

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

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

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

Signature of run method – public void run()

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

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

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

· There are two ways to implement threads.

1. Extend Thread class

· Create a new class, extending the Thread class.

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

· Create an instance of the new class.

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

2. Implement Runnable interface

· Create a new class implementing the Runnable interface.

· Provide a public void run method.

· Create an instance of this class.

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

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

· Call the start method on the Thread.

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

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

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

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

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

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

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

1. Pre-emptive Scheduling.

Ways for a thread to leave running state -

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

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

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

· Solaris JVM’s are pre-emptive.

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

2. Time-sliced or Round Robin Scheduling

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

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

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

· Mactinosh JVM’s

· Windows JVM’s after Java 1.0.2

· Different states of a thread:

1. Yielding

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

· Moves the thread from running to ready state.

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

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

2. Sleeping

· Sleep is also a static method.

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

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

· Throws an InterruptedException.(must be caught)

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

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

3. Suspending

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

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

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

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

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

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

4. Blocking

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

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

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

5. Waiting

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

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

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

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

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

Locks, Monitors and Synchronization

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

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

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

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

· 2 ways to synchronize:

1. Synchronize the entire method

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

· Thread should obtain the object’s lock.

2. Synchronize part of the method

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

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

· wait – points to remember

§ calling thread gives up CPU

§ calling thread gives up the lock

§ calling thread goes to monitor’s waiting pool

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

· notify – points to remember

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

§ notifyAll moves all the threads to ready state

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

· Note the differences between blocked and waiting.

Blocked

Waiting

Thread is waiting to get a lock on the monitor.

(or waiting for a blocking i/o method)

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

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

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

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

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

· Points for complex models:

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

2. Always call notifyAll, instead of notify.

· Class locks control the static methods.

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

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

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

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

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

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

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

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

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

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

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

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