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.