Java Note

§OO

•overriding methods can not have more restrictive access modifier
•overriding methods can throw narrower or fewer exceptions

•overloaded methods can change return typs
•overridding methods can not

•constructors
-this(): invoke constructor
-first line in constructor must be super() or this(), otherwise compiler will add them for you.

§Garbagg collection
•An object is eligible for garbage collection when no live thread can access it.

•Make object eligible for gc
-assign null to an object ref var
-assign object ref var to another obj

•Islands of isolation

•Request GC
-System.gc();
-Runtime rt = Runtime.getRuntim();
rt.gc();

•Java 2 Reference
-Strong ref: can not be gced
-Soft ref: gced when mem is low
-Weak ref: gced in next gc cycle
-Phantom ref: finalized but not gced

§Inner Classes

•Instantiating inner class
-From within outer class
MyInner mi = new MyInner();
-From outside ths outer class
MyOuter.MyInner inner = new MyOuter().new MyInner();

•reference inner class instance within
inner class code
-this
•reference outer this from within inner class code
-MyOuter.this

•Method-Local inner class
-can only be used below class def
-can not use local method var unless it’s final

•Anonymous Inner Class
-to override one or more methods of superclass
-ends with };
-new methods within anonymous inner class can’t be seen outside

•Argument-Defined Anonymous inner class

•static nested class
MyOuter.Nested n = new MyOuter.Nested();

§Thread

•Two ways to create new threads
-extend Thread class
-implement Runnable

•Starting a thread
Runnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();

•Thread name
Thread.currentThread().getName();

•dead thread can never be started again

•Thread states
-new
-runnable
-waiting/blocked/sleeping
-dead

-sleep()
-yield()
-join()
Thread t = new Thread();
t.start();
t.join();
causes current thread to stop until thread t is dead

•synchronization
-only methods can be synchronized
-variables can not be synchronized
-each obj has one and only one lock
-if a thread goes to sleep, it takes locks with it
-a thread can acquire > 1 locks
-ok to have synchronized blocks and synchronize on diff objects

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

This entry was posted in java. Bookmark the permalink.