2.11 years without a post

I like writing about what I am thinking but somehow I have stopped for past 2.11 years after I changed my job. I did not do well though to put an excuse for not writing so I am going to write about many interesting things I found along the way and about my new research on dimensions “From 3 to 2 or 3 to 4

Example : Using Java future, Callable, Executor and CountDownLatch

When you start using java.util.concurrent’s Future and the thread pools or executor framework, Following questions may come to one’s mind

  • How to do thread join kind of operation ?
  • How to set timeout for future?
  • Can the futures notify back the submitting thread when they are done?

Example explaining usage for future, Callable and CountDownLatch together,

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class DataAccessor {
    private static ThreadPoolExecutor executor;
    private int timeout = 100000;
    static {
        executor = new ThreadPoolExecutor(10, 10, 1000, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000));
    }

    public static void main(String[] args) {
        List<String> requests = new ArrayList<String>();
        for(int i=0; i<20; i++){
            requests.add("request:"+i);
        }
        DataAccessor dataAccessor = new DataAccessor();

        List<ProcessedResponse> results = dataAccessor.getDataFromService(requests);
        for(ProcessedResponse response:results){
            System.out.println("response"+response.toString()+"\n");
        }
        executor.shutdown();
    }

    public List<ProcessedResponse> getDataFromService(List<String> requests) {
        final CountDownLatch latch = new CountDownLatch(requests.size());
        List<SubmittedJob> submittedJobs = new ArrayList<SubmittedJob>(requests.size());
        for (String request : requests) {
            Future<ProcessedResponse> future = executor.submit(new GetAndProcessResponse(request, latch));
            submittedJobs.add(new SubmittedJob(future, request));
        }
        boolean isAllDone = false;
        try {
            isAllDone = latch.await(timeout, TimeUnit.MILLISECONDS);
            if (!isAllDone) {
                // some of the jobs not done
                System.out.println("some jobs not done");
            }
        } catch (InterruptedException e1) {
            // take care, or cleanup
            for (SubmittedJob job : submittedJobs) {
                job.getFuture().cancel(true);
            }
        }
        List<ProcessedResponse> results = new LinkedList<DataAccessor.ProcessedResponse>();
        for (SubmittedJob job : submittedJobs) {
            try {
                // before doing a get you may check if it is done
                if (!isAllDone && !job.getFuture().isDone()) {
                    // cancel job and continue with others
                    job.getFuture().cancel(true);
                    continue;
                }
                ProcessedResponse response = job.getFuture().get();
                results.add(response);
            } catch (ExecutionException cause) {
                // exceptions occurred during execution, in any
            } catch (InterruptedException e) {
                // take care
            }
        }
        return results;
    }

    private class SubmittedJob {
        final String request;
        final Future<ProcessedResponse> future;

        public Future<ProcessedResponse> getFuture() {
            return future;
        }

        public String getRequest() {
            return request;
        }

        SubmittedJob(final Future<ProcessedResponse> job, final String request) {
            this.future = job;
            this.request = request;
        }
    }

    private class ProcessedResponse {
        private final String request;
        private final String response;

        ProcessedResponse(final String request, final String response) {
            this.request = request;
            this.response = response;
        }

        public String getRequest() {
            return request;
        }

        public String getResponse() {
            return response;
        }

        public String toString(){
            return "[request:"+request+","+"response:"+ response+"]";
        }
    }

    private class GetAndProcessResponse implements Callable<ProcessedResponse> {
        private final String request;
        private final CountDownLatch countDownLatch;

        GetAndProcessResponse(final String request, final CountDownLatch countDownLatch) {
            this.request = request;
            this.countDownLatch = countDownLatch;
        }

        public ProcessedResponse call() {
            try {
                return getAndProcessResponse(this.request);
            } finally {
                countDownLatch.countDown();
            }
        }

        private ProcessedResponse getAndProcessResponse(final String request) {
            // do the service call
            // ........
            if("request:16".equals(request)){
                throw (new RuntimeException("runtime"));
            }
            return (new ProcessedResponse(request, "response.of." + request));
        }
    }
}

GIDS.WEB 2011; Software Development == Mobile Software Development ?

Today, I have attended the GIDS.WEB 2011 (great indial developer summit) and it came back with mixed feeling about how it went! I have registered myself for the WEB sessions only as I am very interested to see how the new trends and technologies merging? I am not surprised to see that all the presenter are fucusing on mobile / tablet devices in their speech but I am surprised that some are stretching it bit more…In example they just point out mobile devices / tablets for all the topics.

Some useful links on c++ constructor

There are lot of issues around c++ constructors, and I have few links that may help;

http://billharlan.com/pub/papers/Managing_Cpp_Objects.html .

Google code style is a helpfull material for that also.

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Classes

constructors should initialize as a rule all member objects in the initialization list

http://www.parashift.com/c%2B%2B-faq-lite/ctors.html#faq-10.6 .

Constructor Design, MSDN;

http://msdn.microsoft.com/en-us/library/ms229060.aspx .

Copy constructor,

http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Copy_Constructors .

C++ Idioms and Best Practices

http://www.cacr.caltech.edu/~sean/projects/stlib/html/idioms.html .

One very important point (my learning), you should have default constructor defined, either private or public !

Yet another phishing on SBI

Recently got the following mail with nicely arranged phishing page, only it was not https…

Email stating where to visit

The phishing email

The site where it takes and from there the hell / the login page 🙂

You will land on it : first

simple C/C++ Serialization or deflating or Marshalling user defined data types or objects

But is it to use boost or not it is your decision 🙂  It is a good lib. But I find it very handy for small in another way as below;-

// Just a simple serialization in C++
#ifndef CVARIABLELENDATA_HPP
#define CVARIABLELENDATA_HPP

#include &lt;string&gt;

typedef char*	BuffPtr;
typedef size_t	BuffLen;

class CVariableLenData
{
public:
	//Serilizes data members to a char buffer
	void Serialize(BuffPtr &amp;ptr, BuffLen len, BuffLen &amp;writelen) const;

	//DeSerilizes from a char buffer &amp; constructs an object
	static CVariableLenData* DeSerialize(const BuffPtr ptr, BuffLen len);

	void SetData(std::string&amp; str);
	void SetData(int&amp; val);

	CVariableLenData();
private:
	int m_some_int;			// fixed length
	std::string m_some_str; // variable length
	CVariableLenData(const CVariableLenData&amp;);
};

#endif //CVARIABLELENDATA_HPP

// Source file
#include &lt;cstdio&gt;
#include "CVariableLenData.h"

using namespace std;

CVariableLenData::CVariableLenData():m_some_int(0),m_some_str(){}

void CVariableLenData::Serialize(BuffPtr &amp;ptr, BuffLen bufflen, BuffLen&amp; writelen) const
{
	if(!ptr)
		return;
	writelen = _snprintf (ptr, bufflen,"%d", m_some_int);
	*(ptr+writelen) = ' ';		// after each numeric value add an space
	size_t len = writelen + 1;
	// now write the string
	// copy length
	writelen = _snprintf ( (ptr+len), bufflen,"%u", m_some_str.length());
	*(ptr + len ) = ' ';
	len = len + writelen + 1;
	// Copy the data
	memcpy( (ptr+len), m_some_str.c_str(), m_some_str.length());
	writelen = len;
	return;
}

Some links.

Usefull command for Linux Developers

Locating a variable, function or finding a variable, or finding the occurrence / usage of function / variable in an efficient way. For example, you want to find the header file which defines a constant “PATH_MAX”.

    find / -iname *.h | xargs grep -Hn “PATH_MAX”

    or, if you want to redirect the errors, then

    find / -iname *.h 2> /dev/null | xargs grep -Hn “PATH_MAX”