Showing posts with label final. Show all posts
Showing posts with label final. Show all posts

Monday, October 3, 2011

Making collections final

Once we write final
ArrayList list = new ArrayList();

We can add, delete objects from this list, but I can not
list = new ArrayList() or list = list1.

So declaring the list final means that you cannot reassign the list variable to another object.

There are two situations in which this can be useful.
  1. You want to make sure that no-one reassigns your list variable once it has received its value. This can reduce complexity and helps in understanding the semantics of your class/method. In this case you are usually better off by using good naming conventions and reducing method length (the class/method is already too complex to be easily understood).
  2. When using inner classes you need to declare variables as final in an enclosing scope so that you can access them in the inner class. This way, Java can copy your final variable into the inner class object (it will never change its value) and the inner class object does not need to worry what happens to the outer class object while the inner class object is alive and needs to access the value of that variable.


Tuesday, July 5, 2011

Requirements for object to become Hibernate Object

A Hibernate object, suitable for mapping into a database, is a normal java bean with a number of extra requirements.
  • There must be a default constructor for the class.
  • There must be accessors and mutators for all the instance variables of the class. Actually this is overstating the requirement but is a good base rule: read the Hibernate documentation for the full details.
  • The class should implement Serializable. Strictly speaking, this is not a requirement. However, in practice you will normally want your Hibernate objects to be serializable so that they can be (potentially) migrated around a multiprocessor cluster or saved and restored across a web server reboot etc.
  • The class should have an id instance variable, usually of type Long. Again this is not a true requirement but it is recommended to use automatically generated surrogate keys and, if so, to use an instance variable called id to hold it. Certainly, alternatives are possible.
  • The mutator for the id property should be private, not public. Again not a requirement but good practice. You should never update the id property directly but rather rely on Hibernate updating it for you. In practice, it is the value of this field that Hibernate uses to decide if an object has been mapped to a database record or not. Change the property yourself and you could seriously confuse Hibernate.
  • You should decide on a business key for the object and implement the equals and hashCode methods for it.
  • You should add any extra type specific constructors (which should leave the id field null) and business rule methods you like.
  • You should not make the class final if you want to be able to use lazy loading for objects of the class.

Wednesday, June 1, 2011

How do final fields work under the new JMM?

The values for an object's final fields are set in its constructor. Assuming the object is constructed "correctly", once an object is constructed, the values assigned to the final fields in the constructor will be visible to all other threads without synchronization. In addition, the visible values for any other object or array referenced by those final fields will be at least as up-to-date as the final fields.

What does it mean for an object to be properly constructed? It simply means that no reference to the object being constructed is allowed to "escape" during construction. (See Safe Construction Techniques for examples.)  In other words, do not place a reference to the object being constructed anywhere where another thread might be able to see it; do not assign it to a static field, do not register it as a listener with any other object, and so on. These tasks should be done after the constructor completes, not in the constructor.

Now lets see the example:

class FinalFieldExample {
final int x;
int y;
static FinalFieldExample f;
public FinalFieldExample() {
x = 3;
y = 4;
}

}


Now suppose we call the constructor:



new FinalFieldExample();


After the construction, it is guaranteed that x=3 by the thread as x is final. But y's initialization is not guaranteed. It may be seen as 0 or 4. So prior JMM was faulty but now final is "really" final.

 

Difference between new JMM final and old one


Java in old JMM never guaranteed initialization of final objects. But in JMM if final value is set to 3, it will be set, no matter what.

But what if some object like date or array is declared final? If some object is declared final, than all the fields into it and all memory parts of that object are guaranteed to be initialized in new JMM.

So, you can have a final pointer to an array and not have to worry about other threads seeing the correct values for the array reference, but incorrect values for the contents of the array. Again, by "correct" here, we mean "up to date as of the end of the object's constructor", not "the latest value available".

Does final guarantee latest value?


No.

Note: Final values are set by JMM only once. So the "first time initialization" is guaranteed but the latest value is not guaranteed, and of-course final in java really mean that.

Now, having said all of this, if, after a thread constructs an immutable object (that is, an object that only contains final fields), you want to ensure that it is seen correctly by all of the other thread, you still typically need to use synchronization or some other technique to ensure no caching and mutual exclusion. There is no other way to ensure, for example, that the reference to the immutable object will be seen by the second thread. The guarantees the program gets from final fields should be carefully tempered with a deep and careful understanding of how concurrency is managed in your code.

 

Where can't you see effect of final?


 

If FinalFieldExample's constructor looked like this:

public FinalFieldExample() { // bad!
x = 3;
y = 4;
// bad construction - allowing this to escape
global.obj = this;
}


then threads that read the reference to this from global.obj are not guaranteed to see 3 for x.

How can final fields appear to change their values in old Java Memory Model

One of the best examples of how final fields' values can be seen to change involves one particular implementation of the String class.
A String class is immutable in java. So are the wrapper classes like Integer, Double. But they provide corresponding mutable classes like StringBuffer for String and BitSet for Integer. The reason why these classes are immutable because of security. Methods in IO take String as parameter and not StringBuffer. That is because of security reason.
A String can be implemented as an object with three fields ( normal string class have even more, but consider 3 for now) -- a character array, an offset into that array, and a length. So they are:
final char[] buffer = new char[1000];//say 1000;
final int offset;
final int length;


The rationale for implementing String this way, instead of having only the character array, is that it lets multiple String and StringBuffer objects share the same character array and avoid additional object allocation and copying.

Suppose now you call substring() method on this String. A new string is returned by this call.But String.substring() can be implemented by creating a new string which shares the same character array with the original String and merely differs in the length and offset fields. For a String, these fields are all final fields. See - How substring works in Java?

String s1="Kinshuk";
String s2=s1.substring(4);//returns string huk


Now this is 1 parameter substring method which takes beginIndex. So substring starts from 4th character(numbering starts from 0). So it is h.

So now what happens is since substring() returns new String, it will call the constructor. Now constructor will further call Object class constructor, which will call JVM to allocate memory, and further do default initialization and returns the address (or reference) back to new string. But like I said, this array remains the same just the offset and length change. Due to default initialization length and offset have value 0. Now it is possible for the Thread T2 say to see the value of substring s2 and empty because offset and length are 0 due to default initialization rather than 4 and 3 respectively. Another case may be like length is read fine by the thread but not offset. So it may read Kin sometimes and sometimes huk.

The original Java Memory Model allowed this behavior; several JVMs have exhibited this behavior. The new Java Memory Model makes this illegal.

So what is the solution for this?

Some say make constructor synchronized. But this was not a proper solution. Rather Java came up with new JMM and it solved some of the issues.
We'll see this here - How does final fields work under new JVM?

Friday, May 20, 2011

Open Close Principle ( OCP )

The Open-Closed Principle lies at the heart of the object-oriented paradigm. In a sense, we can say that its the goal of our object-oriented designs. Examining a myriad of patterns reveals its application often. It states the following:
Software entities should be open for extension, but closed for modification.

So it has 2 attributes:
  1. Open For Extension - It is possible to extend the behavior of the module as the requirements of the application change (i.e. change the behavior of the module).So classes can be extended
  2. Closed For Modification - Extending the behavior of the module does not result in the changing of the source code or binary code of the module itself.

Example - Violation of OCP
Consider the classes hierarchy:

class Animal
{
     protected String sound;
}

class Cat extends Animal
{
      //getters and setters
}

class Dog extends Animal
{
    //getters and setters
}

Now consider the class, which manages the animals and make them sound.
SoundManager.java
public class SoundManager{
    private List<Animal> animalList;
        
    public SoundManager(){
        animalList = new ArrayList<Animal>();
    }

    public void add(Animal a){
        animalList.add(a);
    }
    public void makeSound(){
        for(Animal a : animalList)
            if(a instanceof Cat)
                makeMew(a);
            else if(a instanceof Dog)
                makeBark(a);
    }
    public void makeMew(Animal a){
        print(a.getSound());
    }
    public void makeBark(Animal a){
        print(a.getSound());
    }

}
Note that this is not a good solution because suppose a new class Lion comes into picture, and it has a sound called roar, you have to edit the code and another if else or switch() to make that work. So it is violation of OCP.

Solution
So a good solution would be to make makeSound function part of class hierarchy itself.

class Animal
{
     protected String sound;
     public abstract void makeSound();  
}

class Cat extends Animal
{
      //getters and setters
     @Override
     public void makeSound(){
          print("mew");
     }
}

class Dog extends Animal
{
    //getters and setters
     @Override
     public void makeSound(){
          print("bark");
     }
}

Now it is much robust to write the above code, no matter how many animals you add.
public class SoundManager{
    private List<Animal> animalList;
        
    public SoundManager(){
        animalList = new ArrayList<Animal>();
    }

    public void add(Animal a){
        animalList.add(a);
    }
    public void makeSound(){
        for(Animal a : animalList)
            a.makeSound();
    }
    //makeBark, makeMew() functionr removed

}

Note of caution
It sems from the 80s and 90s when OO frameworks were built on the principle that everything must inherit from something else and that everything should be subclassable. So for example take a class called Stack in java, it subclasses Vector. So why on earth will you need push and pop if you can directly access element's index?
Joshua Bloch in his famous book "Effective Java" gives the following advice: "Design and document for inheritance, or else prohibit it", and encourages programmers to use the "final" modifier to prohibit subclassing.
So keep in mind, use inheritance only when its compulsory, otherwise try to make your classes final if you feel in future you won't be extending them.

Summary
It should be clear that no significant program can be 100% closed. So we may need to change the code depending on the requirement, but we can try to make our code as robust as possible. Though it comes with experience.

Tuesday, October 19, 2010

Immutable objects

An immutable object is an object which state is guaranteed to stay identical over its entire lifetime. While it is perfectly possible to implement immutability without final, its use makes that purpose explicit, to the human (the software developer) and the machine (the compiler).
Immutable objects carry some very desirable characteristics:
  • they are simple to understand and easy to use
  • they are inherently thread-safe: they require no synchronization
  • they make great building blocks for other objects
Clearly final is going to help us define immutable objects. First in labelling our object as immutable, which makes it simple to use and understand by other programmers. Second in guaranteeing that the object's state never changes, which enable the thread-safe property: thread concurrency issues are relevant when one thread can change data while another thread is reading the same data. Because an immutable object never changes its data, synchronizing access to it is not needed. Create an immutable class by meeting all of the following conditions:
  1. Declare all fields private final.
  2. Set all fields in the constructor.
  3. Don't provide any methods that modify the state of the object; provide only getter methods (no setters).
  4. Declare the class final, so that no methods may be overridden.
  5. Ensure exclusive access to any mutable components, e.g. by returning copies.

Tuesday, September 21, 2010

Const in java (Final)

Defining the constants:
'public static final' variables are constant.
The naming convention for static final variables is to have them in upper case and separate two words with an underscore. For example:
static final int NUMBER_OF_MONTHS = 12;
static final float PI = (float22 7;
If you want to make a static final variable accessible from outside the class, you can make it public too:
public static final int NUMBER_OF_MONTHS = 12;
public static final float PI = (float22 7;
 
Note:
  1. Using the final keyword to declare a variable.
  2. The final keyword specifies that the value of a variable is final and cannot be changed.
  3. It is a convention in Java to write constants in uppercase letters.
  4. Sometimes we have to use enums instead of these simple constants for better readability.
 

Thursday, July 29, 2010

Variables

Variables are temporary data holders. Variable names are identifiers. Variables are declared with a datatype. Java is a strongly typed language as the variable can only take a value that matches its declared type. This enforces good programming practice and reduces errors considerably. When variables are declared they may or may not be assigned or take on a value (initialized). Examples of each of the primitive datatypes available in Java are as follows:

byte x,y,z;             /* 08bits long, not assigned, multiple declaration */
short numberOfChildren; /* 16bits long */
int counter;            /* 32bits long */
long WorldPopulation;   /* 64bits long */

float pi;               /* 32bit single precision */
double avagadroNumber;  /* 64bit double precision */
boolean signal_flag;    /* true or false only */
char c;                 /* 16bit single Unicode character */

Constant variables
Variables can be made constant or read only by prepending the modifier final to the declaration. Java convention uses all uppercase for final variable names.

Local Variables
Local variables (also known as automatic variables) are declared in methods and in code blocks. The automatic variables are not automatically initialized.
A java programmer should explicitly initialize them before first use. These are automatically destroyed when they go out of scope.

Field Variables and Local Variables Field variables are variables that are declared as members of classes. Local variables, also referred to as automatic variables, are declared relative to (or local to) a method or constructor. <

Automatic Initialization Note
Field variables and the elements of arrays are automatically initialized to default values. Local variables are not automatically initialized. Failure to initialize a local variable results in a compilation error.

Final keyword in java

A java variable can be declared using the keyword final. Then the final variable can be assigned only once. You cannot be modify it afterwards. However it can be used in different contexts.

Following are the places where final can be used:

  1. variables: a final variable can be set once and only once.
    blank final variable - A variable that is declared as final and not initialized is called a blank final variable. A blank final variable forces the constructors to initialise it.
  2. fields: a final field can also be set only once, by the constructor of the class which defines it.
  3. methods: a final method cannot be overridden nor hidden.
    final parameters - values of the parameters cannot be changed after initialization.
  4. classes: a final class cannot be extended or inherited.

Other effects of final:

  • Java local classes can only reference local variables and parameters that are declared as final.
  • A visible advantage of declaring a java variable as static final is, the compiled java class results in faster performance.

Notice how using final is an entirely negative act. The final keyword works by subtracting, limiting default language mechanisms: the ability to override a method, to set a variable or a field. The motivations behind using final fall into three broad categories: correctness, robustness, and finally performance. Seeing them 1 by one.

Final Variables

Final variables come in handy in mostly three situations: 

a) Declare Constants

Coupled with static, final is used to flag constants. This usage is well-known to all Java programmers, so I won't expand much on it. It is useful to know that the value of a field declared constant in that manner will be computed statically if possible, at compile-time.
private static final int ERROR_CODE = 1 + 3 * 4 / 2;
public static final String ERROR_MESSAGE = "An error
occurred with code="
+ ERROR_CODE;

The compiler will compute the value for ERROR_CODE, concatenate the string equivalent of the result, and assign the resulting String to ERROR_MESSAGE.


b) Final Parameters

The following sample declares final parameters:




public void doSomething(final int i, final int j){
// ...
}
final is used here to ensure the two indexes i and j won't accidentally be reset by the method. It's a handy way to protect against an insidious bug that erroneously changes the value of your parameters. Generally speaking, short methods are a better way to protect from this class of errors, but final parameters can be a useful addition to your coding style.
Note that final parameters are not considered part of the method signature, and are ignored by the compiler when resolving method calls. Parameters can be declared final (or not) with no influence on how the method is overriden.


c) Anonymous Local Classes

The third situation involving final variables is actually mandated by language semantics. In that situation, the Java compiler won't let you use a variable unless it is declared final. This situation arises with closures, also known as anonymous local classes. Local classes can only reference local variables and parameters that are declared final.





public void doSomething(int i, int j){
final int n = i + j; // must be declared final
Comparator comp = new Comparator() {
public int compare(Object left, Object right) {
return n; // return copy of a local variable
}
};//note the semicolon here
}

The reason for this restriction becomes apparent if we shed some light on how local classes are implemented. An anonymous local class can use local variables because the compiler automatically gives the class a private instance field to hold a copy of each local variable the class uses. The compiler also adds hidden parameters to each constructor to initialize these automatically created private fields. Thus, a local class does not actually access local variables, but merely its own private copies of them. The only way this can work correctly is if the local variables are declared final, so that they are guaranteed not to change. With this guarantee in place, the local class is assured that its internal copies of the variables accurately reflect the actual local variables.


2. Final Fields

A final field can be assigned once and only once, and must be initialized by every constructor of the class that declares it. It is also possible to assign the field directly, in the same statement where it is defined. This simply reflects the fact that such shortcut assignments are compiled into a synthetic constructor. E.g. both the following code samples are correct and strictly equivalent; the first is preferred for being shorter. Initializing outside constructor body

public class MyClass{
//initializing hereitself
private final int i = 2;
}

Initialising in constructor body



public class MyClass{
private final int i;
public MyClass()
{
i = 2;
}
}


3. Using final to Prevent Method Overriding



While method overriding is one of Java’s most powerful features, there will be times when you will want to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden. The following fragment illustrates final:


class A {

final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {

void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}

Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to
do so, a compile-time error will result.

Methods declared as final can sometimes provide a performance enhancement: The compiler is free to inline calls to them because it “knows” they will not be overridden by a subclass. When a small final method is called, often the Java compiler can copy the bytecode for the subroutine directly inline with the compiled code of the calling method, thus eliminating the costly overhead associated with a method call. Inlining is only an option with final methods. Normally, Java resolves calls to methods dynamically, at run
time. This is called late binding. However, since final methods cannot be overridden, a call to one can be resolved at compile time. This is called early binding.



4. Using final to Prevent Inheritance

Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as final, too. As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.
Here is an example of a final class:
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}


As the comments imply, it is illegal for B to inherit A since A is declared as final.


CPP vs Java on Final – Controversy


‘final’ should not be called as constants. Because when an array is declared as final, the state of the object stored in the array can be modified. You need to make it immutable in order not to allow modifcations. In general context constants will not allow to modify. In C++, an array declared as const will not allow the above scenario but java allows. So java’s final is not the general constant used across in computer languages.

A variable that is declared static final is closer to constants in general software terminology. You must instantiate the variable when you declare it static final.

Definition as per java language specification (third edition) – 4.12.4 is “A final variable may only be assigned to once.”(§4.1.2). See notes on final w.r.t Java memory model here -


Java language specification tries to redefine the meaning of constant in the following way!
We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).


Immutable Objects


Final is used to construct immutable objects in java. See – Immutable Objects

Chitika