Tuesday, July 19, 2011

AI and Thread Pool Code Example

Finally uploaded some examples of Breadth-first search, Depth-first search, Best-first search, Genetic Algorithm, Binary search tree, Backward and forward chaining code. Also, I tried to create simple thread pool because I found this pooling idea is very interesting and widely used.

Monday, July 18, 2011

Is it crossroad?

Recently, I have been watching Al Pacino's speech when he won the Academy Award in 1992. He said "I've been very lucky I've found desire for what I do early in my life and have people who encourage that desire."

I also kept Johnny Carson's farewell statement on final Tonight Show. He said "I am one of the lucky people in the world, I found something I always wanted to do, and I have enjoyed every single minute of it."

Steve Jobs also said the same thing. He gave a speech at Stanford Commencement, he said "I was lucky I found what I loved to do early in life... Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven't found it yet, keep looking. Don't settle. As with all matters of the heart, you'll know when you find it. And, like any great relationship, it just gets better and better as the years roll on. So keep looking until you find it. Don't settle."

They got me thinking about my life too, about what my desire is. I have to admit that being a software engineer was not my desire (there was no kid back in 1990s in my school who wanted to be a software engineer I suppose, we usually want to be doctor, pilot, president, etc :p). Software engineering was popular when I was at high school, computers and cellphones were becoming trend back in old days (I'm feeling so old when writing this hahaha...). I then chose to enter Informatics because I want to learn more about computer science. I knew I love math and science, and because I knew that the basic of computer is math logical expression, I thought it shouldn't be a big deal. But I realize it is not my desire to be a software engineer.

I know that great people are them who always follow their hearth and do what they love because you have to love what you do to be great. I wonder if Al Pacino, Steve Jobs, or Johnny Carson ever came to this point of life, at the searching point of their desire. Anyway, what ever it is I am now, all I know is that I always have passion in learning anything new. I always do the best for my job. I learn many new Java frameworks. I love writing and sharing thought and knowledge with others, and I still hope someday I will find what my desire is, either it is in IT field or something else.

Thursday, July 14, 2011

AOP - Notes on Advice

An advice has the following syntax:
advice_type([arg]) : pointcut_name { advice_body }

There are three types of Advice
1. Before, the advice is executed right before the join point code is executed.

Example of a before advice:

/** pointcut */
private pointcut getNameField() : get(private String edu.mat.hello.MessageCommunicator.name);

/** advice */
before() : getNameField() {
System.out.println("Getter method is about to call.");
}

2. After, the advice is executed right after the join point code is executed.

/** pointcut */
private pointcut setNameField() : set(private String edu.mat.hello.MessageCommunicator.name);

/** advice: this advise is executed whether setNameField() returns normally or throwing exception */
after() : setNameField() {
System.out.println("Name has been set.");
}

/** advice: this advise is executed only when setNameField() returns successfully */
after() returning : setNameField() {
System.out.println("Name has been set.");
}

To get the returned object, we can use after() returning(Integer count) : calculateRevenue() {...}

/** advice: this advise is executed only when setNameField() throws exception */
after() throwing : setNameField() {
System.out.println("Name has not been set.");
}

To get the thrown exception, we can use after() throwing (Exception e) : calculateRevenue() {...}

3. Around, this advice is useful to intercept an execution of a join point.

Suppose we have the following pointcut:

private pointcut sayHello(edu.mat.hello.MessageCommunicator caller, String person) : call(* edu.mat.hello.MessageCommunicator.sayHello(String, String)) && args(person, String) && target(caller);

The above pointcut says that we will capture all join points in sayHello(String, String) method of class MessageCommunicator, capture the method caller (target object as shown in target(caller)) and first parameter of the method (as shown in args(person, String)) as stated in pointcut's arguments.

Then we have an advice as in:

void around(edu.mat.hello.MessageCommunicator caller, String person) : sayHello(caller, person) {
try {
proceed(caller, "Pak " + person);
} catch (Exception e) {

} finally {
System.out.println("Say hello finally finished.");
}
}

there, we execute the real join point code in proceed(caller, "Pak " + person); and surround it with try-catch block. The arguments in proceed must match arguments in around().

Tuesday, July 12, 2011

AOP - Notes on Pointcuts

A pointcut has the following syntax: [access specifier] pointcut pointcut-name([args]) : pointcut-definition.

There are five parts of a pointcut as shown above:
1. access specifier
2. pointcut keyword
3. pointcut name
4. pointcut arguments
5. pointcut definition

Pointcut definition consists of pointcut type and pointcut signature, it can be seen as defined-join-point to be captured. To keep things simple, lets list some of the most commonly used pointcut type:

1. execution(MethodSignature) : Method or constructor execution, i.e. execution(public void edu.mat.hello.MessageCommunicator.deliverGlobalMessage(String)) which means capture all join point on the execution of method deliverGlobalMessage in class MessageCommunicator.

2. call(MethodSignature) : Method or constructor call, i.e. call(public void edu.mat.hello.MessageCommunicator.deliverGlobalMessage(String)) which means capture all join points on the calling of method deliverGlobalMessage in class MessageCommunicator.

3. staticinitialization(TypeSignature) : Class initialization, i.e. staticinitialization(edu.mat.hello.MessageCommunicator) which means capture all join points on MessageCommunicator class loading.

4. get(FieldSignature) : Field read access, i.e. get(private String edu.mat.hello.MessageCommunicator.name) which means capture all join points on getter method of private variable name in class MessageCommunicator.

5. set(FieldSignature) : Field write access, i.e. set(private String edu.mat.hello.MessageCommunicator.name) which means capture all join points on setter method of private variable name in class MessageCommunicator.

6. handler(TypeSignature) : Exception handler execution.

7. initialization(ConstructorSignature) : Object initialization, i.e. initialization(public edu.mat.hello.MessageCommunicator.new()) which means capture all join points on object MessageCommunicator creation.

8. within(TypePattern) : Capture join points in a scope, i.e. !within(AccountAspect) && !within(edu.mat.hello.MessageCommunicator) && !within(MessageCommunicatorAspect) which means capture all join points outside AccountAspect aspect and MessageCommunicator class and also outside MessageCommunicatorAspect aspect.

A pointcut could have arguments as shown in the pointcut syntax above. We can capture the values of the arguments using args. For example: private pointcut sayMyName(String person) : call(* edu.mat.hello.MessageCommunicator.sayMyName(String, String)) && args(person, String); which means capture all pointcuts in sayMyName method of class MessageCommunicator and grab first argument (named person) as shown in args(person, String).

We can also capture the caller of being executed join point using target. For example we have the following pointcut private pointcut setNameField() : set(private String edu.mat.hello.MessageCommunicator.name); and private pointcut targetObject(edu.mat.hello.MessageCommunicator object) : target(object) && setNameField();.

In the first pointcut we want to capture all join points on setter method of name variable on class MessageCommunicator. In the second pointcut, we want to capture all join points on previous pointcut (when name variable is set) and grab the MessageCommunicator object which calls that setter method, that is the target.

Database Index, a little action leads to better performance

When you run a query and it happens to run very slow against a certain table, you start thinking that your fellow who created the query must have created a buggy query. Later, when you scan your database tables, you then find that the table has no index at all. Take a deep breath and start creating indexes on columns which are accessed a lot in queries, for example, primary keys, foreign keys, and columns that are used often in the where and order clauses. After that, don't forget to say sorry for blaming your fellow and start complaining your DBA :D.

Monday, July 11, 2011

Entity Object Locking

Object locking is required to avoid concurrency problem in an application. Generally speaking, there are two types of object locking: Pessimistic Locking and Optimistic Locking.

Pessimistic locking is a locking strategy where we prevent users from doing certain things. Here is an example of pessimistic locking:

User A performs update action on an entity object, then user A gets write lock on the being updated entity object. At almost concurrent time, user B performs update action on the same entity object, then user B's action is rejected since the entity object's write lock is being hold by user A.

JPA doesn't support this strategy because it has many disadvantages. It can make the application slower because certain action have to wait for entity object's lock to be released.

Optimistic locking is a locking strategy where we will use object comparison to decide whether a certain transaction will be committed or rolled back. Here is an example of optimistic locking:

When a user performs update action on an entity object, he/she will retrieve a copy of that entity object. Changes are made to the copy object, not the original. When the user is about to save it to database, application checks whether data have been updated since the user retrieved it. If no update has been made, the user gets entity object's write lock, then the data is committed. Otherwise, it is rejected.

JPA support this strategy. It is implemented by adding a column to the table for the entity to save a version number. Every time the row is updated, the version number is incremented. It is by comparing that version number the update action is committed or rejected.

Monday, July 4, 2011

Oracle Toplink + PostgreSQL = nightmare

Banyak masalah yang muncul ketika memakai Oracle Toplink sebagai persistence provider dan PostgreSQL sebagai databasenya, antara lain:
1. Tidak mau menjalankan sequence. Solusi:

package edu.mat.client;

import oracle.toplink.essentials.platform.database.PostgreSQLPlatform;
import oracle.toplink.essentials.queryframework.ValueReadQuery;
import oracle.toplink.essentials.sessions.DatabaseSession;

public class PostgreSQLPlatformSupportingSequences extends PostgreSQLPlatform {

/**
*
*/
private static final long serialVersionUID = -2637524409846222203L;

public boolean shouldNativeSequenceAcquireValueAfterInsert() {
return false;
}

public void platformSpecificSequencingInitialization(DatabaseSession session) {
}

public ValueReadQuery buildSelectQueryForNativeSequence(String seqName,
Integer size) {
ValueReadQuery selectQuery = new ValueReadQuery();
selectQuery.setSQLString("select nextval(\'" + seqName + "\')");
return selectQuery;
}

}

Terus tambahkan di persistence.xml <property name="toplink.target-database" value="edu.mat.client.PostgreSQLPlatformSupportingSequences"/>

2. Muncul error Problem with sequence setup increment does not match its pre-allocation size. Solusi: Ubah current-value di sequence menjadi 100, dan increment-value menjadi genap semisal dua.

3. Data byte dengan annotation @Lob seperti

@Column(name = "PICTURE", table = "USER_PICTURES")
@Lob
@Basic(fetch = FetchType.LAZY)
public final byte[] getPicture() {
return picture;
}

harus didefinisikan dengan tipe oid di PostgreSQL
 

©2009 Stay the Same | by TNB