Nov 29, 2008

Important Points about Threads in Java


  1. To synchronize threads, the Java programming language uses monitors, which are a high-level mechanism for allowing only one thread at a time to execute a region of code protected by the monitor.
  2. The behavior of monitors is explained in terms of locks; there is a lock associated with each object.
  3. The methods wait, notify, and notifyAll of class Object support an efficient transfer of control from one thread to another.
  4. A thread can suspend itself using wait until such time as another thread awakens it using notify.
  5. Each thread has a working memory, in which it may keep copies of the values of variables from the main memory that is shared between all threads.
  6. To access a shared variable, a thread usually first obtains a lock and flushes its working memory. This guarantees that shared values will thereafter be loaded from the shared main memory to the threads working memory.
  7. When a thread unlocks a lock it guarantees the values it holds in its working memory will be written back to the main memory.
  8. Every thread has a working memory in which it keeps its own working copy of variables that it must use or assign. As the thread executes a program, it operates on these working copies. The main memory contains the master copy of every variable.
  9. The main memory also contains locks; there is one lock associated with each object. Threads may compete to acquire a lock.

Jul 25, 2008

Finalization in Java

protected void finalize() throws Throwable

  1. It is declared in Object class.
  2. Is invoked by the garbage collector after it determines that this object is no longer reachable and its space is to be reclaimed.
  3. finalize is that it is invoked if and when the JavaTM virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized.
  4. Subclasses of Object may override this definition.
  5. It is guaranteed that the thread that invokes finalize() will not be holding any user-visible synchronization locks when finalize() is invoked.
  6. Any exception thrown by the finalize() causes the finalization of this object to be halted, but is otherwise ignored.
  7. finalize() is invoked at most once per object, even if execution of this method causes the object to become reachable again and later it becomes unreachable again.