Skip to main content

Divide and Conquer by Java Threads

Suppose you have task which collects the data the from various sources and creates a Object containing all this information e.g. information is distributes over various databases, websites and some you need to calculate based on that data. The single threaded application works fine with small amount of data however as data starts growing single threads shows its limitation.

There is a interesting property of threads which comes to our rescue. Thread maintains the private copy of object on which it operates called as working copy in which it keeps the local modification which are made to the object. While main memory contains the master copy of every object.

After all threads stop executing all the working copies are merged into the master copy. This becomes the curse in case of multiple objects modify the same field in the object because merging back creates the confusion and results in a unpredictable behavior. However if each thread works on the different field of the object merging won't cause a conflict and hence state remains consistent and predictable.

This improves the performance many folds and hence application gain scalability which was missing in the single threaded application.

Snippet:

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        final List list = new ArrayList();
        Person person = null;
        for (int i = 0; i < 100; i++) {
            person = new Person();
            Runnable runnable = createFirstRunnable(person);
            Runnable run = createSecondRunnable(person);
            Thread thread = new Thread(runnable);
            Thread tt = new Thread(run);
            thread.start();
            tt.start();
            list.add(person);
        }

        for (Person p : list) {
            System.out.println("This is " + p.getFirstName() + " " + p.getLastName() + "'s Blog.");
        }
    }

    private static Runnable createSecondRunnable(final Person person) {
        Runnable run = new Runnable() {

            @Override
            public void run() {
                person.setLastName("Gupta");

            }
        };
        return run;
    }

    private static Runnable createFirstRunnable(final Person person) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                person.setFirstName("Subodh");
            }
        };
        return runnable;
    }

    private static class Person {
        private String firstName = null;
        private String lastName = null;

        public Person() {
        }

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    }
}

Comments

Popular posts from this blog

Interview at Progress Software

I have given a lot of interviews before however, this one was special. Let me start from the beginning. I got a call from Progress Software and was scheduled for the first telephonic discussion. Next day, I got a call from HR and she asked me questions on Java and a few basic puzzles.  After clearing the previous round, I got scheduled for the second telephonic interview. This interview covered Java, design-related problems and algorithms. After a week, I got a call from the HR for the onsite interviews in Hyderabad. This is the first time I googled about Progress Software. I said yes for the onsite interviews. Journey to onsite started not as planned after my flight got delayed. Because of fog-related delay in Delhi, I reached the PSI (Progress Software India) office couple of hours late.  HR introduced me to the first interviewer. The interviewer explained the first round. It was a coding round (I am not a big fan of coding rounds), the problem was ...

java.net.SocketException: Connection reset

I am able to fix the problem via setting the following params on the HTTPClient class... client.getParams().setParameter("http.socket.timeout", new Integer(0)); client.getParams().setParameter("http.connection.stalecheck", new Boolean(true)); java.net.SocketException: Connection reset at java.net.SocketInputStream.read(Unknown Source) at java.io.BufferedInputStream.fill(Unknown Source) at java.io.BufferedInputStream.read(Unknown Source) at org.apache.commons.httpclient.HttpParser.readRawLine(HttpParser.java:77) at org.apache.commons.httpclient.HttpParser.readLine(HttpParser.java:105) at org.apache.commons.httpclient.HttpConnection.readLine(HttpConnection.java:1115) at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1832) at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1590) at org.apache.commons.httpclient.HttpMethodBase.execute(...

CXF-RS: Java Code Generation from xml/xsd

Cleaner approach is to use xjc like this: Continue to dirty approach below if u need to: When working with CXF-RS services often we start with XML message that will be served. After that we go through endless iteration of generating the right Java POJO's for the XML. The library like apache XMLBeans generate the Java code but the code generated is not what a developer would write and generally tedious to modify and understand. I have come across a work around for generating Java classes from XSD (xml) which is very close to what a developer with decent experience will write.  Follow the steps given below to explore the solution: 1. Generate the wsdl from from xsd as given in at this link  ( http://cxf.apache.org/docs/xsd-to-wsdl.html ). 2. The Java classes can be generated from wsdl from maven plugin entry below find complete details here   http://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html org.apache.cxf cxf-codegen-plugin ...