Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 776087
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T19:23:42+00:00 2026-05-14T19:23:42+00:00

i have code use googleseach API I want to use Thread to improve speed

  • 0

i have code use googleseach API

I want to use Thread to improve speed of my program. But i have a problem

here is code

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.yahoo.search.WebSearchResult;

/**
 * Simple Search using Google ajax Web Services
 * 
 * @author Daniel Jones Copyright 2006 Daniel Jones Licensed under BSD open
 *         source license http://www.opensource.org/licenses/bsd-license.php
 */

public class GoogleSearchEngine extends Thread {



    private String queryString;
    private int maxResult;
    private ArrayList<String> resultGoogleArrayList = null;



    public ArrayList<String> getResultGoogleArrayList() {
        return resultGoogleArrayList;
    }

    public void setResultGoogleArrayList(ArrayList<String> resultGoogleArrayList) {
        this.resultGoogleArrayList = resultGoogleArrayList;
    }

    public String getQueryString() {
        return queryString;
    }

    public void setQueryString(String queryString) {
        this.queryString = queryString;
    }

    public int getMaxResult() {
        return maxResult;
    }

    public void setMaxResult(int maxResult) {
        this.maxResult = maxResult;
    }

    // Put your website here
    public final static String HTTP_REFERER = "http://www.example.com/";

    public static ArrayList<String> makeQuery(String query, int maxResult) {
        ArrayList<String> finalArray = new ArrayList<String>();
        ArrayList<String> returnArray = new ArrayList<String>();
        try {       
            query = URLEncoder.encode(query, "UTF-8");
            int i = 0;
            String line = "";
            StringBuilder builder = new StringBuilder();
            while (true) {

                // Call GoogleAjaxAPI to submit the query
                URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?start=" + i + "&rsz=large&v=1.0&q=" + query);

                URLConnection connection = url.openConnection();
                if (connection == null) {
                    break;
                }

                // Value i to stop while or Max result
                if (i >= maxResult) {
                    break;
                }

                connection.addRequestProperty("Referer", HTTP_REFERER);

                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }

                String response = builder.toString();
                JSONObject json = new JSONObject(response);
                JSONArray ja = json.getJSONObject("responseData").getJSONArray("results");

                for (int j = 0; j < ja.length(); j++) {
                    try {
                        JSONObject k = ja.getJSONObject(j);     
                        // Break string into 2 parts: URL and Title by <br>

                        returnArray.add(k.getString("url") + "<br>" + k.getString("titleNoFormatting"));
                    } 
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                i += 8;
            }

            // Remove objects that is over the max number result required
            if (returnArray.size() > maxResult) {
                for (int k=0; k<maxResult; k++){
                    finalArray.add(returnArray.get(k));
                }
            }
            else 
                return returnArray;

            return finalArray;
        } 
        catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        //super.run();
        this.resultGoogleArrayList = GoogleSearchEngine.makeQuery(queryString, maxResult);
        System.out.println("Code run here ");
    }
    public  static void main(String[] args) 
    {
        Thread test = new GoogleSearchEngine(); 
        ((GoogleSearchEngine) test).setQueryString("data ");
        ((GoogleSearchEngine) test).setMaxResult(10);
        test.start();   
        ArrayList<String> returnGoogleArrayList = null;
        returnGoogleArrayList = ((GoogleSearchEngine) test).getResultGoogleArrayList();
         System.out.print("contents of al:" + returnGoogleArrayList);       
    }
}

when i run it, it can run into run method but it don’t excute make query methor and return null array.

when i do’t use Thread it can nomal .

Can you give me the reason why ? or give a sulution

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T19:23:42+00:00Added an answer on May 14, 2026 at 7:23 pm

    One of the main problems is that you didn’t wait for the asynchronous computation to complete. You can wait by using Thread.join(), but it’ll be even better if you use a Future<V>, such as a FutureTask<V> instead.

    A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready.

    API links

    • Package java.util.concurrent (contains many high level concurrency utilities)
      • interface Future<V> (represents result of asynchronous computation)
        • interface RunnableFuture<V> (a Future that is Runnable)
          • class FutureTask<V> (implementation that wraps a Callable or Runnable object)
      • interface Executor (“normally used instead of explicitly creating threads”)
      • class Executors (provides factory and utility methods)

    Tutorials and lessons

    • Concurrency
      • High level concurrency objects
    • Concurrency utilities language guide

    See also

    • Effective Java 2nd Edition
      • Item 68: Prefer executors and tasks to threads
      • Item 69: Prefer concurrency utilities to wait and notify
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have some code where I use a thread static object in C#. [ThreadStatic]
I have some code which makes use of Extension Methods, but compiles under .NET
I want C# code to use Socks 5 proxies in Internet Explorer. I have
So I here have such code I use to update CSS if browser supports
I have following code to use google images search API: google.load('search', '1'); function searchComplete(searcher)
I have the following code: use Imager::Screenshot 'screenshot'; my $img = screenshot(hwnd => 'active',
I have the following code: use strict; function isDefined(variable) { return (typeof (window[variable]) ===
hello I have this code that use to sort a datatable. Dim sortingIndex As
I have the following code I use to insert form data into a single
I have the following test code use Data::Dumper; my $hash = { foo =>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.