h1

Example : Using Java future, Callable, Executor and CountDownLatch

January 21, 2012

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

 
public class DataAccessor {
    private static ThreadPoolExecutor executor;
    private int timeout = 1000;
    static {
        executor = new ThreadPoolExecutor(10, 10, 1000,     TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000));
     }
    public ProcessedResponse getDataFromService(List<String> requests) {
        final CountDownLatch latch = new CountDownLatch(requests.size());
        List<Future<SubmittedJob>> submittedJobs = new ArrayList<Future<SubmittedJob>>(
            requests.size());
        for (String request : requests) {
            Future<SubmittedJob> job = executor.submit(new GetAndProcessResponse(request, latch));
            submittedJobs.add(job);
       }
       if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
            // some of the jobs not done
       }
       for (Future<SubmittedJob> job : submittedJobs) {
           try {
               // before doing a get you may check if it is done
               if (!job.isDone()) {
                   // cancel job
                   job.cancel(true);
                   continue;
              }
              ProcessedResponse response = job.get();
              aggregateResponse(response);
         } catch (ExecutionException cause) {
           // exceptions occurred during execution
           // we can get cause.getCause() and check instanceof
        }
    }
 }
private void aggregateResponse(ProcessedResponse response) {
    // aggregate response to a single response.
 }
private class SubmittedJob {
    final Future<ProcessedResponse> job;
    public Future<ProcessedResponse> getJob() {
        return job;
    }
    public String getRequest() {
        return request;
    }
     final String request;
     SubmittedJob(final Future<ProcessedResponse> job, final String request) {
         this.job = job;
         this.request = request;
     }
 }
private class ProcessedResponse {
    ProcessedResponse(final String request) {
    }
 }
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;
    }
    ProcessedResponse call() {
         try {
             return getAndProcessResponse(this.request);
         } finally {
             countDownLatch.countDown();
         }
     }
    private ProcessedResponse getAndProcessResponse(final String request) {
         // do the service call
         // ........
         return (new ProcessedResponse(request));
    }
}
h1

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

April 20, 2011

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.

h1

Some useful links on c++ constructor

April 20, 2011

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 !

h1

Yet another phishing on SBI

January 17, 2011

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

h1

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

September 23, 2010
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 <string>

typedef char*	BuffPtr;
typedef size_t	BuffLen;

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

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

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

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

#endif //CVARIABLELENDATA_HPP

// Source file
#include <cstdio>
#include "CVariableLenData.h"

using namespace std;

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

void CVariableLenData::Serialize(BuffPtr &ptr, BuffLen bufflen, BuffLen& 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.

h1

Usefull command for Linux Developers

September 2, 2010

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”

    h1

    JDBC : Ldap – sql bridge

    September 2, 2010

    I am not able to find a suitable use case for this one. I do not know what requirement it will serve other than maintaining some legacy one. Maybe i am wrong.

    Some links:

    http://www.vogella.de/articles/Eclipse/article.html

    http://myvd.sourceforge.net/jdbcldap.html

    h1

    Some usefull GCC options for preprocessor

    September 2, 2010

    http://sources.redhat.com/gdb/current/onlinedocs/gdb_11.html

    We pass the `-gdwarf-2′ and `-g3′

    flags to ensure the compiler includes information about preprocessor macro. For example;-

    gcc -gdwarf-2 -g3 sample.c -o sample
    
    To print the preprocessor output and stop there :
    
    gcc -E sample.c
    h1

    Future attacks ??

    July 15, 2009

    I liked the article on some remote attacks without network!!! Interesting…….

    http://www.scientificamerican.com/article.cfm?id=hackers-can-steal-from-reflections

    What about analyzing your brain waives..Hah.. Funny… :-)

    h1

    Phishing Attack – An amateur example

    July 14, 2009

    I got an email from some amateur hacker asking me to change my bank account details.

    The email was quite promising, I liked it :-) Here is an screen shot of that from my mailbox :-

    sc4

    After i clicked th URL, the layout was good but the URL that was visible on address bar is really bad, I mean really amateur :-)

    Here is a screen shot of that. I have marked the mistakes :-)

    Screenshot-2

    Follow

    Get every new post delivered to your Inbox.