Saturday, 30 November 2013

Thread Interaction


Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.

Threads exist within a process.every process has at least one. Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.

Multithreaded execution is an essential feature of the Java platform. Every application has at least one thread — or several, if you count "system" threads that do things like memory management and signal handling. But from the application programmer's point of view, you start with just one thread, called the main thread. This thread has the ability to create additional threads
Inter-thread communication (Cooperation):

Cooperation(Inter-thread communication) is all about making synchronized threads communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class:
wait()
notify()
notifyAll()
1)wait() method:

Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. The current thread must own this object's monitor.Syntax:

public final void wait()throws InterruptedException
public final void wait(long timeout)throws InterruptedException
2)notify() method:

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.Syntax:
public final void notify()

3)notifyAll() method:

Wakes up all threads that are waiting on this object's monitor.
public final void notifyAll()

Example of Inter thread Communication:

class Customer{ 
int amount=1000; 
 
synchronized void withdraw(int amount){ 
System.out.println("going to withdraw..."); 
 
if(this.amount<amount){ 
System.out.println("Less balance; waiting for deposit..."); 
try{wait();}catch(Exception e){} 
} 
this.amount-=amount; 
System.out.println("withdraw completed..."); 
} 
 
synchronized void deposit(int amount){ 
System.out.println("going to deposit..."); 
this.amount+=amount; 
System.out.println("deposit completed... "); 
notify(); 
} 
} 
 
class Test{ 
public static void main(String args[]){ 
final Customer c=new Customer(); 
new Thread(){ 
public void run(){c.withdraw(1500);} 
}.start(); 
new Thread(){ 
public void run(){c.deposit(1000);} 
}.start(); 
 
}} 
Output: going to withdraw...
       Less balance; waiting for deposit...
       going to deposit...
       deposit completed...
       withdraw completed

Thursday, 28 November 2013

Preventing Thread Interaction


Java& Threads

Threads are essentially subprocesses1. Informally, you can think of them as tasks that belong to a program and that can run "simultaneously". Depending on the number of CPUs available and the number of competing threads, some of those threads actually will run in parallel on different CPUs, whilst in other cases the illusion of simultaneous execution will be achieved by "juggling" threads in and out of the available CPUs. A part of the OS called the thread scheduler takes care of deciding which threads to allocate CPU time to (on which CPUs) and when.

Recognise conditions that might prevent a thread from executing.


The expression "prevent a thread from executing" is slightly ambiguous, does it mean a thread that has been deliberately paused, or does it also include threads that have died?. A thread that is prevented from executing is said to be blocked.

Reasons a thread may be blocked

A thread may be blocked because

1) It has been put to sleep for a set amount of time

2) It is suspended with a call to suspend() and will be blocked until a resume() message

3) The thread is suspended by call to wait(), and will become runnable on a notify or notifyAll message.


For the purposes of the exam sleep(), and wait/notify are probably the most important of the situations where a thread can be blocked.

The sleep method is static and pauses execution for a set number of milliseconds. There is a version that is supposed to pause for a set number of nanoseconds, though I find it hard to believe many people will work on a machine or Java implementation that will work to that level of accuracy. Here is an example of putting a Thread to sleep, note how the sleep method throws InterruptedException. The thread

public class TSleep extends Thread{
public static void main(String argv[]){
       TSleep t = new TSleep();
       t.start();
       }

       public void run(){
          try{
             while(true){
                  this.sleep(1000);
                  System.out.println("looping while");
                 }
            }catch(InterruptedException ie){}
       }
}

With the release of the Java2 platform the Thread methods stop, suspend and resume have been deprecated (no longer recommended for use, and will produce a warning at compile time). The JDK notes have the contain the following notice

//Quote

Deprecated. This method has been deprecated, as it is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes. For more information see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.

//End Quote

Thread blocking via the wait/notify protocol is covered in the next topic 7.3


Because of the platform dependent nature of Java threading you cannot be certain if a thread will ever give up its use of CPU resources to other threads. On some operating systems the threading algorithm may automatically give different threads a share of the CPU time, on others one thread might simply hog processor resources. For this reason the Java Thread class has a static method called yield which causes the currently running thread to yield its hold on CPU cycles. This thread returns to the "ready to run" state and the thread scheduling system has a chance to give other threads the attention of the CPU. If no other threads are in a "ready to run state" the thread that was executing may restart running again.

It is hard to demonstrate the benefits of using the yield method without being able to run some sample code on two different implementations on Java with different thread scheduling systems. Assuming that option is not available to you it is worth describing two main different scheduling systems used in operating systems.

Time slicing/preemptive

Each thread gets a set amount of CPU time for executing. Once it has used up its time with the CPU, it is removed from accessing the CPU and any other waiting Threads get a chance at CPU time. When each thread has had its chance with the CPU the cycle starts again.The beauty of this approach is that you can be confident that each thread will get at least some time executing.

Non time slicing/Cooperative
A priority system is used to decide which thread will run. A thread with the highest priority gets time with the CPU. A program under this system needs to be created in such a way that it "voluntarily" yield access to the CPU.

The Java Programmers exam does not expect you to understand or know about the system for setting Thread priorities. However it is worthwhile knowing about it, and its limitations so you can understand the importance of using the yield method of the Thread class. The priority of a thread can be set using the Thread.setPriority class and you can find out the priority by using the getPriority method. A newly created Thread gets set to Thread.NORM_PRIORITY.



Wednesday, 27 November 2013

Anonymous Inner Class


An anonymous inner class is really a inner class with no name. They can be used when you only want to make one instance of the class. The use of an anonymous inner class can be a compact way of implementing an event listener:

JButton equalsButton = new JButton("=");
equalsButton.setActionCommand("=");
equalsButton.addActionListener(new ActionListener()
{
     @Override
     public void actionPerformed(ActionEvent event)
      {
            //the code here is executed when the button is clicked.
      }
});
In the above code a JButton is created and instead of assigning a class which implements the ActionListener interface using the addActionListener method we instead write the class itself. The class has no need of a name as it only gets called in the one place. The code for the button click is placed in the actionPerformed method which has the advantage of making it more maintainable because of it's right next to where the button is declared.

Although the syntax might look a llittle more complicated it really is the same as implementing the ActionListener interface in another class. It just has the advantage of being more compact.

Note: An example of the use of implementing an ActionListener by using an anonymous inner class can be found in the A Simple Calculator Handling Button Events step-by-step. The full Java code listing can be found in a Simple Calculator Example Program.
In the JavaLanguage, this is an anonymous specialization of some class or interface. Because it is anonymous and inline, it is necessarily an inner class - i.e., defined within some other class. The following is a popular use of anonymous inner classes:
 addWindowListener(
     new WindowAdapter() {
         public void windowClosing( WindowEvent e ) {
             System.exit(0);
         }
     });
This is the same as the following non-anonymous inner:
 public class WindowClosingAdapter extends WindowAdapter {
     public void windowClosing( WindowEvent e ) {
         System.exit(0);
     }
 }

 ...

 addWindowListener( new WindowClosingAdapter() );
AnonymousInnerClasses can also be used to create something like closures in the JavaLanguage. However they do not "close over" the lexical environment so they aren't TrueClosures?. (They can capture the value of local variables, but they do not have access to the variable binding so they can't change the original variable. Which Java makes quite clear by only allowing InnerClasses to refer to local variables that have been declared final (so no-one can change them)).
Yes. Quite true. So you put the variable in a class -- and then you can change it. ;->
 class IntHolder {
    public int i;
 }
The second example seems much clearer than the first. Naming a class makes the code more readable, even if it requires some extra keystrokes.
Another use of the anonymous inner class is as a shortcut convenience for declaring a local inner class and creating an instance of that class.
        private static LinkedList multiple (LinkedList aList, final int factor) {
            return aList.collect ( new Transform() {
                public int calculate (int n) { return n*factor; }
            });
    }
In this example, the collect() method returns a new list based upon applying a transformation to each element of an existing list. The transformation is specified by the Transform interface. The multiple() method creates an implementation of Transform and an instance in one step. Since we only need one object of this type of transform, we do not need to give the subclass a name.
Here, the syntax for instantiating the anonymous inner class is
    Transform t = new Transform () { /* implementation code */ }

I've used AnonymousInnerClasses to make VirtuallyInitializedAccessors to create inexpensive objects whose lifetimes are just long enough to render a JavaServerPage.

Use Equals methods for comparing String in Java


String class overrides equals method and provides a content equality, which is based on characters, case and order. So if you want to compare two String object, to check whether they are same or not, always use equals() method instead of equality operator. Like in earlier example if  we use equals method to compare objects, they will be equal to each other because they all contains same contents. Here is example of comparing String using equals method.

String name = "Java"; //1st String object
String name_1 = "Java"; //same object referenced by name variable
String name_2 = new String("Java") //different String object

if(name.equals(name_1)){
System.out.println("name and name_1 are equal String by equals method");
}

//this will return false
if(name==name_2){
System.out.println("name_1 and name_2 are equal String by equals method");
}


Difference between == and equals method in Java

Now we know what is equals method, how it works and What is equality operator (==) and How it compare objects, its time to compare them. Here is some worth noting difference between equals() method and == operator in Java:

·          First difference between them is, equals() is a method defined inside the java.lang.Object class and == is one type of operator and you can compare both primitive and objects using equality operator in Java.

·          Second difference between equals and == operator is that, == is used to check reference or memory address of the objects whether they point to same location or not, and equals() method is used to compare the contents of the object e.g. in case of comparing String its characters, in case of Integer its there numeric values etc. You can define your own equals method for domain object as per business rules e.g. two Employes objects are equal if there EmployeeId is same.

·          Third difference between equals and == operator is that, You can not change the behavior of == operator but we can override equals() method and define the criteria for the objects equality.

Let clear all these differences between equals and == operator using one Java example :

String s1=new String("hello");
String s2=new String("hello");


Here we have created two string s1 and s2 now will use == and equals () method to compare these two String to check whether they are equal or not.