Tuesday, December 18, 2007

Implement Your Own Connection Pool

Most large database-oriented applications use a technique called connection pooling to optimize database accessibility. Pooling is basically having a bunch of prepared connections available (already authenticated and ready for use), and leasing them out as needed. Rather than terminate the connection after use, it is returned to the pool for reuse.
Almost all vendors of JDBC drivers implement some sort of connection pooling, and there are many libraries out there that provide this functionality. However, if you want to customize database access with little overhead, it might make sense to implement your own connection pooling. Here is one simple way to do it. This code is built from ideas I came across all over the Internet ...

You can find the source code here. Apart from being efficient, the code also serves to make your data layer portable - can be used with any web server. All you have to do is ensure that the appropriate JDBC driver is available in the classpath, and that the database URL, password, user, and driver class are correct. In NetBeans or Eclipse, you add the JDBC driver by importing the JAR via project properties (libraries). Some IDEs allow you to package the additional libraries in the portable client, so take advantage of it.

The package includes a connection, a driver, and a pool implementation. You can then access them like this:

public class Database {
// Database connection settings
public static String DB_URL = "jdbc:mysql://localhost:3306/timeaccounting";
public static String DB_USER = "root";
public static String DB_PWD = "adminadmin";

public Database() {}

private static SConnectionDriver driver = null;

public static synchronized Connection getConnection() throws SQLException {
if(driver == null) {
try{
driver = new SConnectionDriver(
com.mysql.jdbc.Driver.class.getCanonicalName(),
DB_URL, DB_USER, DB_PWD);
} catch(Exception e){}
}
return DriverManager.getConnection("jdbc:strive:jdcpool");
}

public static void main(String[] args) {
Connection conn = null;
try {
// Obtain a connection from the pool
conn = getConnection();
// Use the connection somehow
if(conn == null) {
System.out.println("Bad connection ...");
} else {
System.out.println("Good connection ...");
}
System.exit(0);
} catch (SQLException ex) {
Logger.getLogger("global").log(Level.SEVERE, null, ex);
} finally {
// Return the connection to the pool
try { conn.close(); } catch (Exception e) {}
}
}
}

In this example, I have a MySQL database called "timeaccounting" that I am interested in accessing, so I set the url, user, and password as shown. I use the singleton approach to determine whether an initial driver has been initialized. Initializing the first driver also creates a pool and is the first connection available. The pool can create more copies as needed, and keep then after use.
It's probably no longer a good practice to use DriverManager (JDBC 1.0, old school), so I'll consider adapting this code to use JNDI soon. Andrew, perhaps you could complete this piece? That one project will need to move to this code ... it's painfully slow because it doesn't use pooling. With this code, your client's desire of database flexibility can be maintained.

Monday, December 17, 2007

Annoying NetBeans IDE Failure ...

I could be the only one experiencing this problem, but while working in NetBeans 6.0, it suddenly disappears on me without warning! It just unceremoniously closes down, almost like its process is suddenly terminated. It's not a JVM crash - that usually leaves traces I can find, but all instances of the JVM are well and running before and after the crash. That means I lose unsaved work and settings - NOT acceptable for a professional IDE! I'm really hoping it's just my environment because this wouldn't be a good testament to the IDE's stability. .
I've seen this issue 3 times in a 2 week span. There are no clues anywhere (not in logs, no popups, nothing ... no trace of what the cause could be), so it is hard to trace this issue to its root. I had seen this issue with beta versions (6.x), but I dismissed it because of the nature of beta software.
I'll keep an eye out for a pattern of failure and see if we can pin this to some issue somewhere. Whether it is on my end or in the IDE, it's not good news.

Saturday, December 01, 2007

Selection Sort With Comparator

Selection sort works by finding the smallest unsorted element in the collection and swapping it with an item in the position that's to be filled next. Because swaps don't happen all the time, this algorithm is a little but more efficient than bubblesort (about 60% better).
The algorithm is a ϑ(n2) complexity computation, efficient enough for small problem sizes. Here's a Java implementation of the algorithm that uses a comparator to specify more complex ordering criteria.

package com.strive.research.algorithms.sorting;

import java.util.Comparator;
import com.strive.research.algorithms.lists.List;
import com.strive.research.algorithms.util.Utilities;

@SuppressWarnings("unchecked")
public class SelectionsortListSorter implements ListSorter {
private final Comparator comparator;

public SelectionsortListSorter(Comparator comparator) {
assert(comparator != null): "Comparator cannot be null";
this.comparator = comparator;
}

@Override
public List sort(List list) {
assert(list != null): "List cannot be null";
int size = list.size();
for(int slot = 1; slot < size - 1; ++slot) {
int smallest = slot;
for(int check = slot + 1; check < size; ++check) {
if(comparator.compare(list.get(check), list.get(smallest)) < 0) {
smallest = check;
}
}
Utilities.swap(list, smallest, slot);
}
return list;
}
}

Bubblesort With Comparator

Bubblesort works by iterating over items in a list and swapping adjucent elements into the required order. Iteration continues until no more swaps are required.
You can make sorting more generic by using comparators. This allows a sorter to sort any collection of data using more complex criteria specified in a comparator. Here's a simple implementation:


package com.strive.research.algorithms.sorting;

import java.util.Comparator;
import com.strive.research.algorithms.lists.List;
import com.strive.research.algorithms.util.Utilities;

@SuppressWarnings("unchecked")
public class BubblesortListSorter implements ListSorter {
private final Comparator comparator;

public BubblesortListSorter(Comparator comparator) {
assert(comparator != null): "Comparator cannot be null";
this.comparator = comparator;
}

@Override
public List sort(List list) {
assert(list != null): "List cannot be null";
int size = list.size();
for(int pass = 1; pass < size; ++pass) {
for(int left = 0; left < (size - pass); ++left) {
int right = left + 1;
if(comparator.compare(list.get(left), list.get(right)) > 0) {
Utilities.swap(list, left, right);
}
}
}
return list;
}
}


The meat of the algorithm is public List sort(List list), which all implementors of my custom ListSorter interface must implement. This algorithm does in-place sorting, so there is no need to return the list really. Bubblesort is a ϑ(n2) complexity computation, efficient enough for small problem sizes.