Data Type Size (Bits) Initial Value Min Value Max Value
Data Type Size (Bits) Initial Value Min Value Max Value
Data Type Size (Bits) Initial Value Min Value Max Value
3. Sub-packages are really different packages, happen to live within an enclosing package.
Classes in sub-packages cannot access classes in enclosing package with default access.
4. Comments can appear anywhere. Can't be nested. No matter what type of comments.
5. At most one public class definition per file. This class name should match the file name. If
there are more than one public class definitions, compiler will accept the class with the file's
name and give an error at the line where the other class is defined.
6. It's not required having a public class definition in a file. Strange, but true. J In this case, the
file's name should be different from the names of classes and interfaces (not public obviously).
8. An identifier must begin with a letter, dollar sign ($) or underscore (_). Subsequent characters
may be letters, $, _ or digits.
9. An identifier cannot have a name of a Java keyword. Embedded keywords are OK. true, false
and null are literals (not keywords), but they can't be used as identifiers as well.
10. const and goto are reserved words, but not used.
11. Unicode characters can appear anywhere in the source code. The following code is valid.
ch\u0061r a = 'a';
char c = '\u0063';
15. Octal literals begin with zero. Hex literals begin with 0X or 0x.
16. Char literals are single quoted characters or unicode values (begin with \u).
17. A number is by default an int literal, a decimal number is by default a double literal.
18. 1E-5d is a valid double literal, E2d is not (since it starts with a letter, compiler thinks that it's
an identifier)
a. Member variables
· Must be initialized explicitly. (Or, compiler will catch it.) Object references can be initialized to
null to make the compiler happy. The following code won't compile. Specify else part or
initialize the local variable explicitly.
String tmp;
return tmp;
· Can have the same name as a member variable, resolution is based on scope.
20. Arrays are Java objects. If you create an array of 5 Strings, there will be 6 objects created.
Declared. (int[] a; String b[]; Object []c; Size should not be specified now)
Allocated (constructed). ( a = new int[10]; c = new String[arraysize] )
Initialized. for (int i = 0; i < a.length; a[i++] = 0)
int a[] = new int[] { 1, 2, 3 }; But never specify the size with the new statement.
23. Java arrays are static arrays. Size has to be specified at compile time. Array.length returns
array's size. (Use Vectors for dynamic purposes).
24. Array size is never specified with the reference variable, it is always maintained with the
array object. It is maintained in array.length, which is a final instance variable.
25. Anonymous arrays can be created and used like this: new int[] {1,2,3} or new int[10]
26. Arrays with zero elements can be created. args array to the main method will be a zero
element array if no command parameters are specified. In this case args.length is 0.
29. Square brackets can come after datatype or before/after variable name. White spaces are fine.
Compiler just ignores them.
30. Arrays declared even as member variables also need to be allocated memory explicitly.
31. Once declared and allocated (even for local arrays inside methods), array elements are
automatically initialized to the default values.
32. If only declared (not constructed), member array variables default to null, but local array
variables will not default to null.
33. Java doesn't support multidimensional arrays formally, but it supports arrays of arrays. From
the specification - "The number of bracket pairs indicates the depth of array nesting." So this can
perform as a multidimensional array. (no limit to levels of array nesting)
34. In order to be run by JVM, a class should have a main method with the following signature.
35. args array's name is not important. args[0] is the first argument. args.length gives no. of
arguments.
38. A class with a different main signature or w/o main method will compile. But throws a
runtime error.
39. A class without a main method can be run by JVM, if its ancestor class has a main method.
(main is just a method and is inherited)
41. Objects (references) are passed by reference. The object reference itself is passed by value.
So, it can't be changed. But, the object can be changed via the reference.
42. Garbage collection is a mechanism for reclaiming memory from objects that are no longer in
use, and making the memory available for new objects.
43. An object being no longer in use means that it can't be referenced by any 'active' part of the
program.
44. Garbage collection runs in a low priority thread. It may kick in when memory is too low. No
guarantee.
45. It's not possible to force garbage collection. Invoking System.gc may start garbage collection
process.
46. The automatic garbage collection scheme guarantees that a reference to an object is always
valid while the object is in use, i.e. the object will not be deleted leaving the reference
"dangling".
47. There are no guarantees that the objects no longer in use will be garbage collected and their
finalizers executed at all. gc might not even be run if the program execution does not warrant it.
Thus any memory allocated during program execution might remain allocated after program
termination, unless reclaimed by the OS or by other means.
48. There are also no guarantees on the order in which the objects will be garbage collected or on
the order in which the finalizers are called. Therefore, the program should not make any
decisions based on these assumptions.
49. An object is only eligible for garbage collection, if the only references to the object are from
other objects that are also eligible for garbage collection. That is, an object can become eligible
for garbage collection even if there are references pointing to the object, as long as the objects
with the references are also eligible for garbage collection.
50. Circular references do not prevent objects from being garbage collected.
51. We can set the reference variables to null, hinting the gc to garbage collect the objects
referred by the variables. Even if we do that, the object may not be gc-ed if it's attached to a
listener. (Typical in case of AWT components) Remember to remove the listener first.
52. All objects have a finalize method. It is inherited from the Object class.
53. finalize method is used to release system resources other than memory. (such as file handles
and network connections) The order in which finalize methods are called may not reflect the
order in which objects are created. Don't rely on it. This is the signature of the finalize method.
In the descendents this method can be protected or public. Descendents can restrict the exception
list that can be thrown by this method.
54. finalize is called only once for an object. If any exception is thrown in finalize, the object is
still eligible for garbage collection (at the discretion of gc)
55. gc keeps track of unreachable objects and garbage-collects them, but an unreachable object
can become reachable again by letting know other objects of its existence from its finalize
method (when called by gc). This 'resurrection' can be done only once, since finalize is called
only one for an object.
56. finalize can be called explicitly, but it does not garbage collect the object.
57. finalize can be overloaded, but only the method with original finalize signature will be called
by gc.
58. finalize is not implicitly chained. A finalize method in sub-class should call finalize in super
class explicitly as its last action for proper functioning. But compiler doesn't enforce this check.
59. System.runFinalization can be used to run the finalizers (which have not been executed
before) for the objects eligible for garbage collection.
Chapter 3 - Modifiers
1. Modifiers are Java keywords that provide information to compiler about the nature of the
code, data and classes.
Only applied to class level variables. Method variables are visible only inside the
method.
Can be applied to class itself (only to inner classes declared at class level, no such thing
as protected or private top level class)
If a class is accessible, it doesn't mean, the members are also accessible. Members'
accessibility determines what is accessible and what is not. But if the class is not
accessible, the members are not accessible, even though they are declared public.
If no access modifier is specified, then the accessibility is default package visibility. All
classes in the same package can access the feature. It's called as friendly access. But
friendly is not a Java keyword. Same directory is same package in Java's consideration.
'private' means only the class can access it, not even sub-classes. So, it'll cause access
denial to a sub-class's own variable/method.
These modifiers dictate, which classes can access the features. An instance of a class can
access the private features of another instance of the same class.
'protected' means all classes in the same package (like default) and sub-classes in any
package can access the features. But a subclass in another package can access the
protected members in the super-class via only the references of subclass or its subclasses.
A subclass in the same package doesn't have this restriction. This ensures that classes
from other packages are accessing only the members that are part of their inheritance
hierarchy.
Methods cannot be overridden to be more private. Only the direction shown in following
figure is permitted from parent classes to sub-classes.
3. final
You may, if necessary, defer initialization of a final local variable. Simply declare the
local variable and initialize it later (for final instance variables. You must initialize them
at the time of declaration or in constructor).
final variables cannot be changed (result in a compile-time error if you do so )
Method arguments marked final are read-only. Compiler error, if trying to assign values
to final arguments inside the method.
Member variables marked final are not initialized by default. They have to be explicitly
assigned a value at declaration or in an initializer block. Static finals must be assigned to
a value in a static initializer block, instance finals must be assigned a value in an instance
initializer or in every constructor. Otherwise the compiler will complain.
Final variables that are not assigned a value at the declaration and method arguments that
are marked final are called blank final variables. They can be assigned a value at most
once.
Local variables can be declared final as well.
If a final variable holds a reference to an object, then the state of the object may be
changed by operations on the object, but the variable will always refer to the same object.
This applies also to arrays, because arrays are objects; if a final variable holds a
reference to an array, then the components of the array may be changed by operations on
the array, but the variable will always refer to the same array
A blank final instance variable must be definitely assigned at the end of every
constructor of the class in which it is declared; otherwise a compile-time error occurs.
A class can be declared final if its definition is complete and no subclasses are desired
or required.
A compile-time error occurs if the name of a final class appears in the extends clause
of another class declaration; this implies that a final class cannot have any subclasses.
A compile-time error occurs if a class is declared both final and abstract, because the
implementation of such a class could never be completed.
Because a final class never has any subclasses, the methods of a final class are never
overridden
4. abstract
3. if it doesn't provide implementation to any of the methods in an interface that it says
implementing.
Just terminate the abstract method signature with a ';', curly braces will give a compiler
error.
A class can be abstract even if it doesn't have any abstract methods.
5. static
Can be applied to nested classes, methods, variables, free floating code-block (static
initializer)
Static variables are initialized at class load time. A class has only one copy of these
variables.
Static methods can access only static variables. (They have no this)
Actually, static methods are not participating in the usual overriding mechanism of
invoking the methods based on the class of the object at runtime. Static method binding is
done at compile time, so the method to be invoked is determined by the type of reference
variable rather than the actual type of the object it holds at runtime.
Let's say a sub-class has a static method which 'overrides' a static method in a parent
class. If you have a reference variable of parent class type and you assign a child class
object to that variable and invoke the static method, the method invoked will be the
parent class method, not the child class method. The following code explains this.
}
class Parent {
System.out.println(x);
}
System.out.println(x);
}
}
6. native
Written in a non-Java language, compiled for a single machine target type.
Java classes use lot of native methods for performance and for accessing hardware Java
is not aware of.
Native method signature should be terminated by a ';', curly braces will provide a
compiler error.
native doesn't affect access qualifiers. Native methods can be private.
System.loadLibrary is used in static initializer code to load native libraries. If the
library is not loaded when the static method is called, an UnsatisfiedLinkError is
thrown.
7. transient
Can be applied to class level variables only.(Local variables cannot be declared
transient)
Transient variables may not be final or static.(But compiler allows the declaration, since
it doesn't do any harm. Variables marked transient are never serialized. Static variables
are not serialized anyway.)
Not stored as part of object's persistent state, i.e. not written out during serialization.
8. synchronized
9. volatile
Declaring a variable volatile indicates that it might be modified asynchronously, so that
all threads will get the correct value of the variable.
No access
modifier
private N Y Y Y Y N
final Y Y (Except Y Y N N
anonymous
classes)
abstract Y Y (Except N Y N N
anonymous
classes)
static N Y Y Y N Y (static
initializer)
native N N N Y N N
transient N N Y N N N
synchronize N N N Y N Y (part of
d method, also need
to specify an
object on which a
lock should be
obtained)
volatile N N Y N N N
Implementing OO relationships
"has a" relationship is implemented by providing the class with member variables.
Overloading Overriding
Signature has to be different. Just a Signature has to be the same. (including the
difference in return type is not return type)
enough.
Accessibility may vary freely. Overriding methods cannot be more private
than the overridden methods.
Exception list may vary freely. Overriding methods may not throw more
checked exceptions than the overridden
methods.
Just the name is reused. Methods are Related directly to sub-classing. Overrides the
independent methods. Resolved at parent class method. Resolved at run-time based
compile-time based on method on type of the object.
signature.
Can call each other by providing Overriding method can call overridden method
appropriate argument list. by super.methodName(), this can be used only
to access the immediate super-class's method.
super.super won't work. Also, a class outside the
inheritance hierarchy can't use this technique.
Methods can be static or non-static. static methods don't participate in overriding,
Since the methods are independent, it since they are resolved at compile time based on
doesn't matter. But if two methods the type of reference variable. A static method
have the same signature, declaring in a sub-class can't use 'super' (for the same
one as static and another as non-static reason that it can't use 'this' for)
does not provide a valid overload. It's
a compile time error.
s1 = s2;
}
class S1 {
public String getS() {
return s;
}
return s;
}
In the above code, if we didn't have the overriding getS() method in the sub-class and if we call the
method from sub-class reference variable, the method will return only the super-class member
variable value. For explanation, see the following points.
Also, methods access variables only in context of the class of the object they belong to. If a
sub-class method calls explicitly a super class method, the super class method always will
access the super-class variable. Super class methods will not access the shadowing variables
declared in subclasses because they don't know about them. (When an object is created,
instances of all its super-classes are also created.) But the method accessed will be again
subject to dynamic lookup. It is always decided at runtime which implementation is called.
(Only static methods are resolved at compile-time)
String s = "main";
}
class S1 {
String s = "S1";
return s;
}
void display() {
System.out.println(s);
}
String s = "S2";
void display() {
}
}
With OO languages, the class of the object may not be known at compile-time (by virtue of
inheritance). JVM from the start is designed to support OO. So, the JVM insures that the
method called will be from the real class of the object (not with the variable type declared).
This is accomplished by virtual method invocation (late binding). Compiler will form the
argument list and produce one method invocation instruction - its job is over. The job of
identifying and calling the proper target code is performed by JVM.
JVM knows about the variable's real type at any time since when it allocates memory for an
object, it also marks the type with it. Objects always know 'who they are'. This is the basis of
instanceof operator.
Sub-classes can use super keyword to access the shadowed variables in super-classes. This
technique allows for accessing only the immediate super-class. super.super is not valid. But
casting the 'this' reference to classes up above the hierarchy will do the trick. By this way,
variables in super-classes above any level can be accessed from a sub-class, since variables
are resolved at compile time, when we cast the 'this' reference to a super-super-class, the
compiler binds the super-super-class variable. But this technique is not possible with
methods since methods are resolved always at runtime, and the method gets called
depends on the type of object, not the type of reference variable. So it is not at all possible
to access a method in a super-super-class from a subclass.
}
class STGrandParent {
}
}
}
}
//super.super.getWealth();
((STParent)this).getWealth();
// Calls Child method, due to dynamic method lookup
((STGrandParent)this).getWealth();
System.out.println(((STParent)(this)).wealth);
System.out.println(((STGrandParent)(this)).wealth);
An inherited method, which was not abstract on the super-class, can be declared abstract
in a sub-class (thereby making the sub-class abstract). There is no restriction.
In the same token, a subclass can be declared abstract regardless of whether the super-
class was abstract or not.
Private members are not inherited, but they do exist in the sub-classes. Since the private
methods are not inherited, they cannot be overridden. A method in a subclass with the
same signature as a private method in the super-class is essentially a new method,
independent from super-class, since the private method in the super-class is not visible in
the sub-class.
}
class PTSuper {
public void hi() { // Super-class implementation always calls superclass hello
hello();
}
private void hello() { // This method is not inherited by subclasses, but exists in
them.
// The test will then print "hello-Super" for all three calls
System.out.println("hello-Super");
}
}
public void hi() { // This method overrides super-class hi, calls subclass hello
try {
hello();
}
catch(Exception e) {}
}
void hello() throws Exception { // This method is independent from super-class
hello
System.out.println("hello-Sub");
}
Private methods are not overridden, so calls to private methods are resolved at compile
time and not subject to dynamic method lookup. See the following example.
}
class PolyA {
Constructors are not inherited as normal methods, they have to be defined in the class itself.
If you define no constructors at all, then the compiler provides a default constructor
with no arguments. Even if, you define one constructor, this default is not provided.
We can't compile a sub-class if the immediate super-class doesn't have a no argument
default constructor, and sub-class constructors are not calling super or this explicitly
(and expect the compiler to insert an implicit super() call )
A constructor can call other overloaded constructors by 'this (arguments)'. If you
use this, it must be the first statement in the constructor. This construct can be used
only from within a constructor.
A constructor can't call the same constructor from within. Compiler will say '
recursive constructor invocation'
A constructor can call the parent class constructor explicitly by using 'super
(arguments)'. If you do this, it must be first the statement in the constructor. This
construct can be used only from within a constructor.
Obviously, we can't use both this and super in the same constructor. If compiler sees
a this or super, it won't insert a default call to super().
Constructors can't have a return type. A method with a class name, but with a return
type is not considered a constructor, but just a method by compiler. Expect trick
questions using this.
Constructor body can have an empty return statement. Though void cannot be
specified with the constructor signature, empty return statement is acceptable.
Only modifiers that a constructor can have are the accessibility modifiers.
Initializers are used in initialization of objects and classes and to define constants in
interfaces. These initializers are :
Cannot pass on the checked exceptions. Must catch and handle them.
Cannot pass on the checked exceptions. Must catch and handle them.
Used to factor out code that is common to all the constructors.
Also useful with anonymous classes since they cannot have constructors.
All constructors must declare the uncaught checked exceptions, if any.
In all the initializers, forward referencing of variables is not allowed. Forward
referencing of methods is allowed.
2. static initializer block execution. (in the order of declaration, if multiple
blocks found)
Interfaces:
All methods in an interface are implicitly public, abstract, and never static.
All variables in an interface are implicitly static, public, final. They cannot be
transient or volatile. A class can shadow the variables it inherits from an interface,
with its own variables.
A top-level interface itself cannot be declared as static or final since it doesn't make
sense.
Same case with final, synchronized, native. Classes can declare the methods to be
final, synchronized or native whereas in an interface they cannot be specified like
that. (These are implementation details, interface need not worry about this)
But classes cannot implement an interface method with a static method.
If an interface specifies an exception list for a method, then the class implementing
the interface need not declare the method with the exception list. (Overriding methods
can specify sub-set of overridden method's exceptions, here none is a sub-set). But if
the interface didn't specify any exception list for a method, then the class cannot
throw any exceptions.
All interface methods should have public accessibility when implemented in class.
Interfaces cannot be declared final, since they are implicitly abstract.
A class can implement two interfaces that have a method with the same signature or
variables with the same name.
Inner Classes
A class can be declared in any scope. Classes defined inside of other classes are
known as nested classes. There are four categories of nested classes.
Very much like any-other package level class / interface. Provide an extension to
packaging by the modified naming scheme at the top level.
Interfaces are implicitly static (static modifier also can be specified). They can
have any accessibility modifier. There are no non-static inner, local or anonymous
interfaces.
An instance of a non-static inner class can exist only with an instance of its
enclosing class. So it always has to be created within a context of an outer
instance.
Just like other non-static features of a class. Can access all the features (even
private) of the enclosing outer class. Have an implicit reference to the enclosing
instance.
Defined inside a block (could be a method, a constructor, a local block, a static
initializer or an instance initializer). Cannot be specified with static modifier.
Cannot have any access modifier (since they are effectively local to the block)
Can access all the features of the enclosing class (because they are defined inside
the method of the class) but can access only final variables defined inside the
method (including method arguments). This is because the class can outlive the
method, but the method local variables will go out of scope - in case of final
variables, compiler makes a copy of those variables to be used by the class. (New
meaning for final)
Since the names of local classes are not visible outside the local context,
references of these classes cannot be declared outside. So their functionality could
be accessed only via super-class references (either interfaces or classes). Objects
of those class types are created inside methods and returned as super-class type
references to the outside world. This is the reason that they can only access final
variables within the local block. That way, the value of the variable can be always
made available to the objects returned from the local context to outside world.
Cannot be specified with static modifier. But if they are declared inside a static
context such as a static method or a static initializer, they become static classes.
They can only access static members of the enclosing class and local final
variables. But this doesn't mean they cannot access any non-static features
inherited from super classes. These features are their own, obtained via the
inheritance hierarchy. They can be accessed normally with 'this' or 'super'.
Anonymous classes are defined where they are constructed. They can be created
wherever a reference expression can be used.
Anonymous classes cannot have explicit constructors. Instance initializers can be
used to achieve the functionality of a constructor.
Keywords implements and extends are not used in anonymous classes.
Abstract classes can be specified in the creation of an anonymous class. The new
class is a concrete class, which automatically extends the abstract class.
Inner classes can have synchronous methods. But calling those methods obtains the
lock for inner object only not the outer object. If you need to synchronize an inner
class method based on outer object, outer object lock must be obtained explicitly.
Locks on inner object and outer object are independent.
Nested classes can extend any class or can implement any interface. No restrictions.
All nested classes (except anonymous classes) can be abstract or final.
Classes can be nested to any depth. Top-level static classes can be nested only within
other static top-level classes or interfaces. Deeply nested classes also have access to
all variables of the outer-most enclosing class (as well the immediate enclosing
class's)
Member inner classes can be forward referenced. Local inner classes cannot be.
An inner class variable can shadow an outer class variable. In this case, an outer
class variable can be referred as (outerclassname.this.variablename).
Outer class variables are accessible within the inner class, but they are not inherited.
They don't become members of the inner class. This is different from inheritance.
(Outer class cannot be referred using 'super', and outer class variables cannot be
accessed using 'this')
An inner class variable can shadow an outer class variable. If the inner class is sub-
classed within the same outer class, the variable has to be qualified explicitly in the
sub-class. To fully qualify the variable, use classname.this.variablename. If we don't
correctly qualify the variable, a compiler error will occur. (Note that this does not
happen in multiple levels of inheritance where an upper-most super-class's variable is
silently shadowed by the most recent super-class variable or in multiple levels of
nested inner classes where an inner-most class's variable silently shadows an outer-
most class's variable. Problem comes only when these two hierarchy chains
(inheritance and containment) clash.)
If the inner class is sub-classed outside of the outer class (only possible with top-
level nested classes) explicit qualification is not needed (it becomes regular class
inheritance)
Chapter 7 Threads
· When a thread begins execution, the scheduler calls its run method.
· 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)
· 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.
· Provide a public void run method, otherwise empty run in Thread class will be
executed.
· Call start method on the instance (don't call run - it will be executed on the same
thread)
· Target should implement Runnable, Thread class implements it, so it can be a
target itself.
· 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.
· It can get pre-empted by a high-priority thread, which becomes ready to execute.
· 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.
1. Yielding
· 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
· 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.
· 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.
· 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.
· 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.
· 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 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.
§ one thread gets moved out of monitor's waiting pool to ready state
§ Thread gets to execute must re-acquire the lock of the monitor before it can proceed.
Blocked Waiting
Thread is waiting to get a lock on Thread has been asked to wait.
the monitor. (by means of wait method)
1. Always check monitor's state in a while loop, rather than in an if statement.
· 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.
· 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.