Wednesday, May 1, 2013

The Final Keyword


As you may already know the final keyword can be used in a method declaration to indicate that the method cannot be overridden by subclasses. Also if you declare a class as final, you prevent any subclasses from being derived from it. If you use it in a variable declaration, means that the value of a variable is final and must not be changed and that the compiler will check your code for any violations of this and flag them as errors.

But one particular use of the final keyword is a very important and often overlooked weapon in your concurrency armoury. Essentially, final can be used to make sure that when you construct an object, another thread accessing that object doesn't see that object in a partially-constructed state, as could otherwise happen. This is because when used as an attribute on the variables of an object, final has the following important characteristic as part of its definition:
When the constructor exits, the values of final fields are guaranteed to be visible to other threads accessing the constructed object.
The final field is a means of what is sometimes called safe publication. Here, "publication" of an object means creating it in one thread and then having that newly-created object be referred to by another thread at some point in the future. When the JVM executes the constructor of your object, it must store values into the various fields of the object, and store a pointer to the object data. As in any other case of data writes, these accesses can potentially occur out of order, and their application to main memory can be delayed and other processors can be delayed unless you take special steps to combat this. In particular, the pointer to the object data could be stored to main memory and accessed before the fields themselves have been committed (this can happen partly because of compiler ordering: if you think about how you'd write things in a low-level language such as C or assembler, it's quite natural to store a pointer to a block of memory, and then advance the pointer as you're writing data to that block). And this in turn could lead to another thread seeing the object in an invalid or partially constructed state.

final prevents this from happening: if a field is final, it is part of the JVM specification that it must effectively ensure that, once the object pointer is available to other threads, so are the correct values of that object's final fields.

The fields on any object accessed via a final reference are also guaranteed to be at least as up to date as when the constructor exits. This means that:

Values of final fields, including objects inside collections referred to by a final reference, can be safely read without synchronization.
Note that if you have a final reference to a collection, array, or some other mutable object, you must still synchronize all accesses to that object (or use a thread-safe collection such as a ConcurrentHashMap) if that collection is ever accessed by a thread other than the constructing thread.

Tuesday, July 19, 2011

Tuning JDBC

I was trying to create a common method to execute querys when I start wondering which type of Statement to used, PreparedStatement, CallableStatement or Statement. So I start doing some research about it, here are my findings :

Statement is not precompiled, prepared statements are precompiled, hence prepared statement will be faster than statement”. My next question would be “What precompile means?”. When you execute a SQL query, database server will prepare an execution plan before executing the actual query, this execution plan will be cached at database server for further execution. The extra benefit you get by using CallableStatement is that allow you to execute database stored procedures.

From what I found my guess was that the PreparedStatement will be faster, so I run a test to see which of the three performs better. Here are the response times when retrieving 4000 records.


#Samples Avg(Millis)
Statement
2520046
PreparedStatement
2520261
CallableStatement
25
20174

As you can see from the previous table the difference between the three was not significant, I was expecting that the Prepared Statement will outperforms the others. But what I noticed was that the response times of the three were very poorly for retrieving 4000 records, so I keep doing research and find out that there is a setting you can change to increase performance when retrieving data, the fetch size.

The fetch size is the number of rows physically retrieved from the database at one time by the JDBC driver as you scroll through a ResultSet with the next() method (Usually default is 10). If you set the query fetch size to 100, when you retrieve the first row, the JDBC driver retrieves at once the first 100 rows (or all of them if fewer than 100 rows satisfy the query). When you retrieve the second row, the JDBC driver merely returns the row from local memory it doesn't have to retrieve that row from the database. This feature improves performance by reducing the number of calls (which are frequently network transmissions) to the database. To set the query fetch size, use the setFetchSize() method on the Statement (or PreparedStatement or CallableStatement) before execution.

The optimal fetch size is not always obvious. Usually, a fetch size of one half or one quarter of the total expected result size is optimal. Here are the new times for the same amount of records(4000) using a fetch size of 100, 500 and 1000.


#Samples Avg(Millis) Fetchsize 100 Avg(Millis) Fetchsize 500 Avg(Millis) Fetchsize 1000
Statement 25 2454 1008 874
PreparedStatement 25 2604 1018 919
CallableStatement 25 2460 988 959

As you can see from the table the response times decreased considerably by increasing the fetch size but keep in mind that If you set the fetch size much larger than the number of rows retrieved, it's likely that you'll get a performance decrease, not an increase. I did another test with 70 rows and the response times increase when I set up the fetch size to 1000.

Wednesday, July 13, 2011

Java 7

Last week was the release of Java 7 and how Mark Reinhold mention it in the presentation the most significant thing is that is finally out, because is the first new version of Java in five years, and the first since Oracle took over Sun. This is not a revolutionary release is more as a evolutionary release, here is a list of some of the new features available:
  • Strings in switch
  • Automatic Resource Management
  • Improved Type Inference for Generic Instance Creation (diamond)
  • Simplified Varargs Method Invocation
  • VM support for non-Java languages (InvokeDynamic)
  • Annotations on Java types
  • A New File System API
Even though I only listed a few features there is a lot more new stuff in this release. I personally like the automatic resource management because this will make your code more clear and smaller and what I think is more important it will give you a more concise error handling. Also the new file system API have a lot of new interesting features like the Watch Service. So, what are you wating for? download it now and start playing with it.

Wednesday, September 30, 2009

Java Management Extensions (JMX)

I know it's been a long time since my last post, I been very busy and now I just want to talk a little bit about JMX, a topic I came across while doing some light reading; Professional Java 6.

JMX is a technology for managing and monitoring applications systems and network devices. This technology allows you to deploy specialized java classes called MBeans to a software agent and interact with them at runtime.

I hope this sparks a little bit of interest in that developer brain of yours.... any who, I will publish a code example in my next post.

Tuesday, July 14, 2009

Phone Book with Jdbc Implementation.

For those of you that are interested in the solution of Saturday's exercise, click here to download the code.

Saturday, July 11, 2009

Saturday's Class

Click here to download the code for today's example.

Friday, July 10, 2009

Today's code

Click here to download the code for today's class.

Saturday, July 4, 2009

Saturdays Class

Click here to download the code for todays examples.

Friday, July 3, 2009

Magic Squares

For those of you that are interested in the algorithm to solve magic squares, click here to download the code. By the way here is the link for today's class.

Friday, June 26, 2009

Exceptions

An exception in Java is an object that’s created when an abnormal situation arises in your program. This exception object has fields that store information about the nature of the problem. The exception is said to be thrown—that is, the object identifying the exceptional circumstance is tossed as an argument to a specific piece of program code that has been written specifically to deal with that kind of problem. The code receiving the exception object as a parameter is said to catch it.

Types of Exceptions

An exception is always an object of some subclass of the standard class Throwable. Two direct subclasses of the class Throwable the class Error and the class Exception cover all the standard exceptions. Both these classes themselves have subclasses that identify specific exception conditions.

The exceptions that are defined by the Error class and its subclasses are characterized by the fact that they all represent conditions that you aren’t expected to do anything about, so you aren’t expected to catch them. Error has three direct subclasses—ThreadDeath, LinkageError, and VirtualMachineError.

For almost all the exceptions that are represented by subclasses of the Exception class, you must include code in your programs to deal with them if your code may cause them to be thrown. If a method in your program has the potential to generate an exception of a type that has Exception as a superclass, you must either handle the exception within the method or register that your method may throw such an exception. If you don’t, your program will not compile.

Dealing with Exceptions

Whenever you write code that can throw an exception, you have a choice. You can supply code within the method to deal with any exception that is thrown, or you can essentially ignore it by enabling the method containing the exception throwing code to pass it on to the code that called the method.

To declare that your method can throw exceptions you just put the throws keyword after the parameter list for the method.

double myMethod() throws IOException {
// Detail of the method code...
}


If you want to deal with the exceptions where they occur, you can include three kinds of code blocks in a method to handle them try, catch, and finally blocks.

  • A try block encloses code that may give rise to one or more exceptions. Code that can throw anexception that you want to catch must be in a try block.
  • A catch block encloses code that is intended to handle exceptions of a particular type that maybe thrown in the associated try block. I’ll get to how a catch block is associated with a tryblock in a moment.
  • The code in a finally block is always executed before the method ends, regardless of whether any exceptions are thrown in the try block.
The structure of the try, catch, finally is show in the next code :


try {
// Code that can throw one or more exceptions
} catch(Exception e) {
// Code to handle the exception
} finally {
// Clean-up code to be executed last
}


To demonstrate the use of Exceptions and how can you create your own I created a quick example. Click here to download the code.

Polymorphism

The word polymorphism generally means the ability to assume several different forms or shapes. In programming terms it means the ability of a single variable of a given type to be used to reference objects of different types and to automatically call the method that is specific to the type of object the variable references. This enables a single method call to behave differently, depending on the type of the object to which the call applies.

To demonstrate the use of Interfaces and Polymorphism I created a small example. Click here to download the code.

Interfaces

An interface is essentially a collection of related constants and/or abstract methods, and in most cases it will contain just methods. An interface doesn’t define what a method does. It just defines its form, its name, its parameters, and its return type, so by definition the methods in an interface are abstract.

The Universe Superclass

All the classes that you define are subclasses by default. All your classes have a standard class, Object, as a base, so Object is a superclass of every class. You never need to specify the class Object as a base in the definition of your classes it happens automatically. Your classes will inherit members from the class Object. These all happen to be methods, of which seven are public, and two are protected. The seven public methods are:

MethodPurpose
toString()This method returns a String object that describes the current object. In the inherited version of the method, this will be the name of the class, followed by ‘@’ and the hexadecimal representation for the object. This method is called automatically when you concatenate objects with String variables using +. You can override this method in your classes to return your own String object for your class.
equals()This compares the reference to the object passed as an argument with the reference to the current object and returns true if they are equal. Thus true is returned if the current object and the argument are the same object (not just equal—they must be one and the same object). It returns false if they are different objects, even if the objects have identical values for their data members.
getClass()This method returns an object of type Class that identifies the class of the current object.
hashCode()This method calculates a hashcode value for an object and returns it as type int. Hashcode values are used in classes defined in the package java.util for storing objects in hash tables.
notify()This is used to wake up a thread associated with the current object.
notifyAll()This is used to wake up all threads associated with the current object.
wait()This method causes a thread to wait for a change in the current object.


The two protected methods that your classes inherit from Object are:

MethodPurpose
clone()This will create an object that is a copy of the current object regardless of type. This can be of any type, as an Object variable can refer to an objectof any class. Note that this does not work with all class objects and does not always do precisely what you want.
finalize()This is the method that is called to clean up when an object is destroyed.


To show you how can you take advantage of the Object class I created a simple example. Click here to download the code.

Abstract Classes

An abstract class is a class in which one or more methods are declared, but not defined. The bodies of these methods are omitted, because implementing the methods does not make sense. Since they have no definition and cannot be executed, they are called abstract methods. The declaration for an abstract method ends with a semicolon and you specify the method with the keyword abstract to identify it as such. To declare that a class is abstract you just use the keyword abstract in front of the class keyword in the first line of the class definition.

To demonstrate the use of abstract classes I modified the last example. Click here to download the code.

Class Inheritance

Defining a new class based on an existing class is called derivation. The new class, or derived class, is referred to as a direct subclass of the class from which it is derived. The original class is called a base class because it forms the base for the definition of the derived class. The original class is also referred to as a superclass of the derived class.

The inclusion of members of a base class in a derived class so that they are accessible in that derived class is called class inheritance. An inherited member of a base class is one that is accessible within the derived class. If a base class member is not accessible in a derived class, then it is not an inherited member of the derived class, but base class members that are not inherited still form part of a derived class object.

To demonstrate the use of class inheritance I created a quick example, click here to download the code.

The finalize() method

You have the option of including a method finalize() in a class definition. This method is called automatically by Java before an object is finally destroyed and the space it occupies in memory is released. In practice this may be some time after the object is inaccessible in your program. When an object goes out of scope, it is dead as far as your program is concerned, but the Java Virtual Machine may not get around to disposing of the remains until later. When it does, it calls the finalize() method for the object.

protected void finalize() {
    // Your clean-up code...
}


I modified the classes from "our first project" to demonstrate it. Click here to download the updated classes.

Nested Classes

When you define a nested class, it is a member of the enclosing class in much the same way as the other class members. A nested class can have an access attribute just like other class members, and the accessibility from outside the enclosing class is determined by the attributes in the same way:

public class Outside {
    // Nested class
    public class Inside {
        // Details of Inside class...
    }
    // More members of Outside class...
}


Static Nested Classes

To make objects of a nested class type independent of objects of the enclosing class type, you can declare the nested class as static. A static nested class can have static members, whereas a non-static nested class cannot.

To demonstrate the use of a nested class I created a partial implementation of a LinkedList, click here to download the code.

Encapsulation

Encapsulation refers to the hiding of items of data and methods within an object. This is achieved by specifying them as private in the definition of the class. Being able to encapsulate members of a class in this way is important for the security and integrity of class objects. You may have a class with data members that can take on only particular values. By hiding the data members and forcing the use of a method to set or change the values, you can ensure that only legal values are set.

Another major advantage of encapsulation is the ability to hide the implementation of a class. By allowing only limited access to the members of a class, you have the freedom to change the internals of the class without necessitating changes to programs that use the class. Click here to download the code that demonstrate encapsulation.

Controlling Access to Class Members

The options you have for specifying the accessibility of a variable or a method in a class are:
AttributePermitted Access
No access attributeFrom methods in any class in the same package
publicFrom methods in any class anywhere as long as the class has been declared as public
privateAccessible only from methods inside the class. No access from outside the class at all.
protectedFrom methods in any class in the same package and from any subclass anywhere.
This may sound more complicated than it actually is. The following image shows the access allowed between classes within the same package.



The next image shows the access allowed between classes in different packages.

The Variable this

Every instance method has a variable with the name this that refers to the current object for which the method is being called. The compiler uses this implicitly when your method refers to an instance variable of the class. You could put it in yourself, but there’s no need, the compiler does it for you. In fact, it is not good practice to clutter up your code with this unnecessarily.

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter. The names of variables that are declared within a method are local to the method. You can use a name for a local variable or a parameter in a method that is the same as that of a instance variable. If you find it necessary or convenient to do this, then you must use the name this when you refer to the data member of the class from within the method. The variable name by itself will always refer to the variable that is local to the method, not the instance variable. For example, suppose you wanted to add a method to change the radius of a Sphere object to a new radius value that is passed as an argument. You could code this as:

void changeRadius(double radius) {
    // Change the instance variable to the argument value
    this.radius = radius;
}


No confusion in the duplication of names exists here. It is clear that you are receiving a radius value as a parameter with the name radius and storing it in the radius variable for the class object.