Saturday 30 November 2013

Creating an Eclipse Java project



Now that the basic elements of the Workbench have been explained, here are some instructions for creating a simple project. New projects, folders, and files can be created using several different approaches. In this section resources will be created using three different approaches:
Project Explorer's view context menu
New Wizard button
A project can be created using the File menu. Once the project has been created a folder and file can be created as well
The steps below outline how to create a Java project using many of the default settings to make it easy to get started.
From the main workbench window, click File > New > Project. The New Project wizard opens.
Select Java Project and click Next.
In the Project name field, type a name for your new Java project, like myJavaProject.
For Location, choose Create project in workspace and for the Project Layout, select Use project folder as root for sources and class files.
Click the Next button, then Finish.
You may be prompted about switching to the Java Perspective. Answer Yes to this question.
The Package Explorer view now shows your new Java project.

Thursday 28 November 2013

Benefits of Encapsulation


Java Object-Orientation

This Object-Oriented programming page includes the following





This web page does not dive deep into OO concepts (there are numerous books on the subject that are far better explaining the OO concepts than me) but outlines the basic OO concepts and any rules that you need to know, again this is intended to be a quick guide.

OOP encapsulates data (attributes) and methods (behaviors) into objects, the data and methods are intimately tied together, implementation details are hidden within the objects themselves. In Java the unit of programming is the class from which objects are eventually instantiated. Methods and data are encapsulated within the walls of the class. A class contains the data and the methods that access the data contained within the class. The data contained in a class is called the instance variables.

Encapsulation

The ability to make changes in your implementation code without breaking the code of others who use your code is a key benefit of encapsulation. You want to hide (mask) implementation details behind a public programming interface. By interface we mean the set of accessible methods your code makes available for other code to call, in other words, your codes API's. You can change the code without forcing a change in the code that calls your changed methods.

To provide maintainability, flexibility and extensibility you must encapsulate the code and to do this you

Keep your instance variables protected (using the private access modifier)
Make public accessor methods and force coding to use those methods
For the methods use the JavaBeans naming convention (set (mutator) and get (accessor) methods)
Set and Get methods 
public class Football {
    private String team;                  // this is hidden to the outside world
    private int groundCapacity;           // this is hidden to the outside world

   public void setTeam(String t) { ... }
   public String getTeam() { ... }

   public void setGroundCapacity(int c) { ... }
   public int getGroundCapacity { ... }
}

Note: the only way to get to the instance variables is via the set and get methods

When you create a new class that does something you will document only what access methods (get and set) are available to the public and this will not change, whoever implements your class can get updates and improved versions knowing that implementing this newer version will not break his/her program as the return types and passing variables to methods will be the same.

State the benefits of encapsulation in object oriented design and write code that implements tightly encapsulated classes .
Encapsulation

The principle of encapsulation is that all of an object’s data is contained and hidden in the object and access to it restricted to methods of that class.

Code outside of the object cannot (or at least should not) directly access object fields.
All access to an object’s fields takes place through its methods.

Change the way in which the data is actually stored without affecting the code that interacts with the object
Validate requested changes to data
Ensure the consistency of data — for example preventing related fields from being changed independently, which could leave the object in an inconsistent or invalid state
Protect the data from unauthorized access
Perform actions such as notifications in response to data access and modification

Encapsulation is the principal of keeping the internal details of a classes state and behaviours hidden from the other classes that use it. This allows you to change those details where necessary, without breaking compatibility. The interconnectness between pieces of code is called 'coupling', and minimising it makes for more reusable and maintainable classes. The expectated behaviour of a class or method is referred to as its 'contract'. You do not want to expose any more than the minimum required to support the contract, or you can end up with tangled interdependent code with poor maintainabilty, and in all likelyhood, poor quality.

Encapsulation also aids polymorphism and inheritance - if the internal details of a class are exposed and used, it is very hard to substitute a different implementation of the same contract.

To achieve good encapsulation, make everything have the tightest possible access control so if something should not be used in a given context, limit the access to prohibit it. In particular, class instance variables should be private, and accessed only through 'get'/'set' methods (a.k.a accessors and mutators). This would allow you to do some work or checking before reading/writing a value to the variable. You could remove the variable entirely and derive it or obtain it from another source. If the variable was public, and was accessed directly, should changes would break client code.

Wednesday 27 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.


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.

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.



Benefits of Encapsulation


Java Object-Orientation

This Object-Oriented programming page includes the following

This web page does not dive deep into OO concepts (there are numerous books on the subject that are far better explaining the OO concepts than me) but outlines the basic OO concepts and any rules that you need to know, again this is intended to be a quick guide.

OOP encapsulates data (attributes) and methods (behaviors) into objects, the data and methods are intimately tied together, implementation details are hidden within the objects themselves. In Java the unit of programming is the class from which objects are eventually instantiated. Methods and data are encapsulated within the walls of the class. A class contains the data and the methods that access the data contained within the class. The data contained in a class is called the instance variables.


The ability to make changes in your implementation code without breaking the code of others who use your code is a key benefit of encapsulation. You want to hide (mask) implementation details behind a public programming interface. By interface we mean the set of accessible methods your code makes available for other code to call, in other words, your codes API's. You can change the code without forcing a change in the code that calls your changed methods.

To provide maintainability, flexibility and extensibility you must encapsulate the code and to do this you

Keep your instance variables protected (using the private access modifier)
Make public accessor methods and force coding to use those methods
For the methods use the JavaBeans naming convention (set (mutator) and get (accessor) methods)
Set and Get methods 
public class Football {
    private String team;                  // this is hidden to the outside world
    private int groundCapacity;           // this is hidden to the outside world

   public void setTeam(String t) { ... }
   public String getTeam() { ... }

   public void setGroundCapacity(int c) { ... }
   public int getGroundCapacity { ... }
}

Note: the only way to get to the instance variables is via the set and get methods

When you create a new class that does something you will document only what access methods (get and set) are available to the public and this will not change, whoever implements your class can get updates and improved versions knowing that implementing this newer version will not break his/her program as the return types and passing variables to methods will be the same.


The principle of encapsulation is that all of an object’s data is contained and hidden in the object and access to it restricted to methods of that class.

Code outside of the object cannot (or at least should not) directly access object fields.
All access to an object’s fields takes place through its methods.

Change the way in which the data is actually stored without affecting the code that interacts with the object
Validate requested changes to data
Ensure the consistency of data — for example preventing related fields from being changed independently, which could leave the object in an inconsistent or invalid state
Protect the data from unauthorized access
Perform actions such as notifications in response to data access and modification

Encapsulation is the principal of keeping the internal details of a classes state and behaviours hidden from the other classes that use it. This allows you to change those details where necessary, without breaking compatibility. The interconnectness between pieces of code is called 'coupling', and minimising it makes for more reusable and maintainable classes. The expectated behaviour of a class or method is referred to as its 'contract'. You do not want to expose any more than the minimum required to support the contract, or you can end up with tangled interdependent code with poor maintainabilty, and in all likelyhood, poor quality.

Encapsulation also aids polymorphism and inheritance - if the internal details of a class are exposed and used, it is very hard to substitute a different implementation of the same contract.

To achieve good encapsulation, make everything have the tightest possible access control so if something should not be used in a given context, limit the access to prohibit it. In particular, class instance variables should be private, and accessed only through 'get'/'set' methods (a.k.a accessors and mutators). This would allow you to do some work or checking before reading/writing a value to the variable. You could remove the variable entirely and derive it or obtain it from another source. If the variable was public, and was accessed directly, should changes would break client code.