Thursday, March 19, 2009

Timer in Android ( The Better Way )

The usual Timer class is available in Android, but unless you are doing non-trivial stuff, its better to use Handler for scheduling task. Why? Well, Timer class introduces a new thread and while developing mobile application, you should really think twice (or more than that!) before using it.

So, how jobs can be scheduled using Handler class? There are two different approaches. First, You can ask it to send messages at some later time by using sendMessageAtTime(Message, long) or sendMessageDelayed(Message, long) , which then can be processed as shown in my previous post, effectively acting as a timer. Secondly, you can directly ask it to run some scheduled task by using postAtTime(Runnable, long) and postDelayed(Runnable, long).

The methods described here lets you schedule a single shot task. To repeat a scheduled task, you have to register it again to run for the next time. So, assuming that you want to repeat a task after one second delay, we can do something like this,


private Handler handler = new Handler();


private Runnable runnable = new Runnable() {

public void run() {

doStuff();

/*
* Now register it for running next time
*/


handler.postDelayed(this, 1000);
}


};

To stop a repeated task you can use removeCallbacks(Runnable r), which removes all pending Runnable r in the message queue.

Sunday, February 15, 2009

For First Time GSoC Applicants

Google Summer of Code for 2009 has been announced. In GSoC 2008, I applied and worked for Jato. It was really fun. Moreover it helped me to be a better developer than I had been. While doing my GSoC, I have learned git, under-the-hood details about Java and become a more matured C programmer. It also helped to shake off the initial intimidation factors in joining open source community as a developer for the first time. Before GSoC, I didn't even know the name of Jato, but now I am an active developer continuing my GSoC works.

Thats why I want to share what I have learned. I know there are plenty of resources available for GSoC wanna be applicants, but for the first-timers the initial process may be very confusing. Thats the audience on which I will focus.

So here it goes.

1. Start Early

Yes, start early, start Now ! Do not wait for the last moment. Go through the faqs, tutorials. Dig into the previous 2008, 2007, 2006, 2005 GSoC pages. Get an idea about the mentors that participated and projects that have been proposed. But it is important to keep in mind that no previous mentor organization is guaranteed to have a slot in GSoC.


2. Come up with a short list

As there are many organizations participating in GSoC now, it is necessary to make a list of organizations that you think suits you most. And I think, its better to make that list even before the announcement of accepted mentor list. Because without any sort of prior list and plan, you may run out of time if you need to go through all the accepted mentors and their projects one by one. Of course, there is a certain not-so-amazing possibility that your selected mentor failed to get a slot this year but, hey, you can certainly make changes in that case.

You can start sorting by using language. If you abhor loosely typed language there is no point in applying php, JavaScript focused mentors. Here is a list of mentors in 2008, categorized by language.

Another important factor in choosing the mentors apart from language that they use, might be the type of the work they do. Are you interested in working on compilers ? How about diving into GPS/Geospatial projects? Here is another nice categorized list of 2008 mentors that might help you to guess.

While traversing previous years' mentors list, you can find that even though officially no mentoring organization is guaranteed to have a slot, most well known mentors, for example apache, mozilla or pidgin, are almost sure to have slots. Thats the source of another dilemma. Because, well known mentors mean more fierce competition, while lesser known mentors are less likely to have slots. I had to face this problem. I chose to work on Plan 9 from Bell Labs. After reading lots of documents, doing lots of trying and testing with Inferno, it failed to get a grant. So, my advice is to come up with a balanced list.


3. Get in touch now

After choosing the list, its necessary to get in touch with the organization. Join the mailing list, hang in the IRC channel.

Read the mails carefully, watch the conversations in IRC. Most probably the 'hot' topics for upcoming gsoc will be discussed. Find out the steps and protocols for committing code.

And most importantly, try to get the culture in the organization. Some organization may be very strict. You might get burnt for Top-Posting or get a sharp 'RTFM' reply for asking something which has been answered else where. But thicken your skin for that. We all certainly make mistake, do say things which we later regret. The important thing is to learn from the mistakes and not to let the intimidation factor trade on you.

And particularly if this is your first approach to an open source community, you may lay low for few days both in IRC and mailing lists. Try to understand the environment, the pattern of conversations, which is allowed to ask and which is not. But don't hesitate to participate if the topic is in your level. It'll certainly help you to bond with your new developer colleagues.



4. Land on an Idea

Try hard to come up with an idea. Certainly, you can choose ideas from the proposed idea-list. But coming up with an idea can and will boost your chance to get accepted. While proposing idea, try hard to come up with original and ambitious idea which the organization actually 'needs'.

To come up with such ideas, you may need to start reading the development docs and go through few source code files. It is necessary to do so to find out how and where your idea fits and whether its feasible to complete within the GSoC time line (3 months approximately).

After coming up with an idea, the most important thing is to communicate with the organization. Propose the idea in details, get a feedback. That will make a strong case for your application.


I think it concludes the initial preparation. The next important step will be writing application. Here is some link for that

  1. http://drupal.org/node/59037
  2. http://inkscape.org/wiki/index.php/SOC_Writing_Project_Proposals
  3. http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/194477
  4. http://www.postgresql.org/developer/summerofcodeadvice.html
  5. http://developer.pidgin.im/wiki/SoCDiscussions

Tuesday, February 3, 2009

WeakReference? What is that !

Even though weak references are massively useful features available for fairly long time, I think they are pretty overlooked. ( Yeah, I am pretty bemused by getting multiple "WeakReference? huh! whats that?!" responses on a single day.) So, lets refresh on what weak references are and what they do.

In short, weak references can save you from a lot of problems in case of unintentional object retention. If you don't understand "Unintentional Object Retention" mumbo-jumbo, here is a scenario for you.

Lets say, you need to use gigantic images in your application. But, as you know loading images each time from disk is pretty expensive, you decided to cache it. And as a sane person, you don't want the gigantic images using up a large chunk of memory when there is no reference to it. Now, how can you do that? If you use normal reference to the image ( to place it in vector or hash map or in your custom cache class ), when GC will run, it will find that it has at least a reference to that image and would refrain itself from finalizing and reclaiming the memory. Now what you can do is, keeping some kind of in house count of the references that point to that image and when there is no other reference pointing, you can remove the holding reference from your cache store making it eligible for garbage collection. Is it fun to mimic the garbage collector? Hell, No !

Here comes the mighty weak reference into play. To put simply weak references are not strong enough to force the referent object to remain in memory. Another mumbo-jumbo? Well, lets go into details.

Each ordinary reference in Java is a strong reference. What make them strong is the way they interact with GC. More particularly, if an object is reachable through a chain of strong reference it will not be claimed by GC. So for two ordinary references x and y, the following statement

x = y;

will make sure that the object to which y points would be kept in memory as long as x is reachable.

But, for a weak reference, that is not the case. If all the references to a particular object are weak references ( we call this situation "weakly reachable"), then garbage collector is eligible to claim the object. So if you use WeakReference, like the following

WeakReference<SomeOtherRef> weakReference = new WeakReference(someOtherRef);

you are making sure that garbage collector's reachability has been increased and later you can get the reference by using

weakReference.get();

The point to remember is that it is not enough strong to prevent from garbage collection, so don't surprise if get() all on a sudden, starts returning null.

So, by now you have got what you need for that caching mechanism. In your caching store house, you will use WeakReference so that when there is no other strong references, the gigantic image is gracefully removed by the GC.

Java provides more control over garbage collection by providing PhantomReference, SoftReference, ReferenceQueue and WeakHashMap. But I think I have enough for today, so all these have to wait.

Sunday, February 1, 2009

A first look into Android Thread

I have started looking into Android. Late to join the show? well, may be, but surely its pretty exciting.

I have tried to build a utility class that can do Network I/O. And grasping things was little hard at first. Network I/O or other heavy-duty stuff in Android should be done on other worker thread. Because doing it in main thread (or the UI thread) can ( and will ) make your application unresponsive and may be killed as the system is persuaded to think that it has hung. For every Android developer, this is a must-read.

So you have to do the long running operations in separate thread. And to interact between threads you have to resort to Handler. A Handler is used to send message or runnable to a particular thread. The thing to remember is that a Handler is associated with the MessageQueue of the single thread which has created it. After creating a Handler, it can be used to post message or runnable to that particular thread.

Here is an example



public class MyActivity extends Activity {

void startHeavyDutyStuff() {

// Here is the heavy-duty thread
Thread t = new Thread() {

public void run() {
while (true) {

mResults = doSomethingExpensive();

//Send update to the main thread
messageHandler.sendMessage(Message.obtain(messageHandler, mResults));
}

}
};
t.start();
}

// Instantiating the Handler associated with the main thread.
private Handler messageHandler = new Handler() {

@Override
public void handleMessage(Message msg) {
switch(msg.what) {
//handle update
//.....
}
}

};
}





So what is done here? Very simple. A Handler has been created which is bound to the message queue of the main thread. And by using the handler, from the heavy-duty, worker thread we send message to the main thread to be processed.

Feeling like drinking from hose-pipe? Dont worry, I'll post more realistic example soon.

Tuesday, August 12, 2008

Providing synchronization support in Jato

When I started to work on monitorenter and monitorexit, I thought it would be quite easy. Get the reference, call the lock/unlock function, done. But, soon after beginning, I was chanting "nothing-is-what-it-seems" mantra.

For monitorenter and monitorexit, it is necessary to provide support for goto and athrow bytecode instructions. Here is why.

Providing support for athrow instruction was easy. As Jato still does not support exception handling, actually nothing but function for bytecode consuming and dummy instruction selection rule was necessary.

But, for goto, I ran into a bug in control flow analyzer. So, after few hours of debugging, did fix that bug. And every thing was easy there after.

Then sent flood of patches! YAY !

( I made some nasty formatting horrors, which were fixed by Pekka. Thanks Pekka. )

Monday, July 28, 2008

The 64 Bit and premature optimaization anomaly !

I am currently working to improve my undergrad research on Neural Network (which has been accepted in Fifth International Symposium On Neural Networks ).We have done a lot of brain storming in last few months. And then I was selected to translate the whole idea to code ! Having the sole responsibility for developing the whole idea does involve twist and turns, but it is fun too ! After finishing developing , I have a feeling that it is gonna be a good work.

And last night, my research partner informed me that , result has improved for every case but for benchmark heart attack problem. For this data set the program falls into an infinite loop.

In constructing neural network, instead of maintaining a explicit relationship of which node connected to which one, I have packed the connection information in unsigned integer. So storing and retrieving the connection information is easy, just a few left or right shift and masking .

As a matter of fact, this optimization is not very necessary here, because

1) Storing and retrieving connection information do not occur that much.

2) As it is a research on how neural network can predict result more accurately , result is of more concern not the speed.


But now, as heart attack benchmark problem has 35 input nodes, way more than other benchmark problems, I am left shifting an unsigned integer by 35 bits !. Phew ! Guess what Donald. E. Knuth has told us

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." (Knuth, Donald. Structured Programming with go to Statements, ACM Journal Computing Surveys, Vol 6, No. 4, Dec. 1974. p.268.)


But as changing it would cause an avalanche of more changes, I did the obvious, changed the data type from unsigned integer to unsigned long long. And the result is same, trapped in the infinite loop.

So after more debugging for 2 hours, when I am cursing under my breath, the following line just hit me

connection_matrix_value+=1<<(edge->get_forward_node()->get_node_id()+

shifting_value_for_forward_node);

Here, 1 is of type int having length 32 bits, so shifting it by 32 or more bits, nothing retains, the net result is a big fat 0 !. So what i need to do is making 1 as unsigned long long type ( 1ULL ).

And, YAY ! everything works !

Friday, July 25, 2008

Update On Jato

Well , everything seems little scattered.

<*>store and <*>load is almost done , but cant check whether it actually works or not because of its dependency on register allocation.

instanceof is done but a little code re-structuring is needed.


For monitorenter and monitorexit , parsing and code generation is done, but need to handle athrow as well.


Haven't looked into checkcast yet.

And the deadline is August 18. Gotta run !.