Friday, October 22, 2010

Looping in different Threads?

My last post ends with looping in different threads. Yes, that is not clear enough to understand what it is. Let check some situation where this may applicable.
In google app engine, It is a request based engine, where http request will be placed and our application should process and provide result back. But we have a limitation; each request should return within 30 seconds. But google app engine provides a task queue implementation where we can post request to that queue and which will be executed later. So, say if we want to process a request which last more than 30 seconds we should split that into small parts and post to task queue.
Mostly, if we want to process a collection, then we will go for looping. But in the case of google app engine, for every item of that collection, we should post request one after other by holding a counter in bigTable (google app engine datastore) .
Here if you see this we are looping a collection but each item will be processed in different threads.
Ok, Now think a senario where you want to loop from middle to end and start of a collection then we need to find some better way.

Thursday, October 14, 2010

Looping (count/2*(count%2==2?1:-1)) from middle to start and end.

Have you ever loop from middle to end and start of any list. i.e the index should move something like 0,1,-1,2,-2,3,-3 ...
One of the following would do:
1.
for(int i = 0 ; i < 5;i++){
System.out.println(i);
System.out.println(i*-1);
}

2.
for(int i =1 ; i <10;i++){
System.out.println(i/2*(i%2==0?1:-1));
}

of course, first one will print 0 two times. So,

1.1.
System.out.println(0);
for(int i = 1 ; i < 5;i++){
System.out.println(i);
System.out.println(i*-1);
}

Let me change these suitable for real situation:

1.1.
doSomethingForIndex(0)
for(int i = 1 ; i < 5;i++){
doSomethingForIndex(i);
doSomethingForIndex(0);
}

2.
for(int i =1 ; i <10;i++){
doSomethingForIndex(i/2*(i%2==0?1:-1));
}

If you look at these you will see no different in execution, because all statements run one after other.
But, say if we want to run doSomethingForIndex(i); in different threads one after other, then sample 1.1 will run two statements in one thread. So in that case it is better to go for option 2. (count/2*(count%2==2?1:-1))