I am writing a program which uses Random.ORG api. When I click calculate button, JProgressBar starts right after the opeartion is being done and stay freezed until this moment.
I tried extra try-catch clauses, if statements and bool-gates. None of them worked, how could I fix it?
kazananiBelirleButon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
try {
HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
System.out.println(randoms.toString());
String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{\"random\":") + "}";
System.out.println(tarihiYazdir(test,14));
cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
sonucPane.setText("\n"+sonuclariYazdir(test,0));
} catch (RandomOrgSendTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgKeyNotRunningError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientRequestsError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientBitsError e1) {
System.out.print("lol");
e1.printStackTrace();
} catch (RandomOrgBadHTTPResponseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgRANDOMORGError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgJSONRPCError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
Swing is single threaded. Calling listeners, painting/updating UI all happen on a single thread called the Event Dispatch Thread (EDT).
Since you do all your work in the event handler code, the Swing UI cannot be updated until you return from your method (actionPerformed()).
Read this tutorial: Concurrency in Swing
What you should do is do your time-consuming work in a separate thread and only do short tasks in the EDT (e.g. UI updates).
Also check out the SwingWorker class which is designed to perform lengthy GUI-interaction tasks in a background thread.
Try using swing worker in your method.
Swing Worker
Here is an example from old version of swing worker. Firs you need to add SwingWorker class to your project:
import javax.swing.SwingUtilities;
/**
* This is the 3rd version of SwingWorker (also known as
* SwingWorker 3), an abstract class that you subclass to
* perform GUI-related work in a dedicated thread. For
* instructions on using this class, see:
*
* http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
*
* Note that the API changed slightly in the 3rd version:
* You must now invoke start() on the SwingWorker after
* creating it.
*/
public abstract class SwingWorker
{
private Object value; // see getValue(), setValue()
private Thread thread;
/**
* Class to maintain reference to current worker thread
* under separate synchronization control.
*/
private static class ThreadVar
{
private Thread thread;
ThreadVar(Thread t)
{
thread = t;
}
synchronized Thread get()
{
return thread;
}
synchronized void clear()
{
thread = null;
}
}
private ThreadVar threadVar;
/**
* Get the value produced by the worker thread, or null if it
* hasn't been constructed yet.
*/
protected synchronized Object getValue()
{
return value;
}
/**
* Set the value produced by worker thread
*/
private synchronized void setValue(Object x)
{
value = x;
}
/**
* Compute the value to be returned by the <code>get</code> method.
*/
public abstract Object construct();
/**
* Called on the event dispatching thread (not on the worker thread)
* after the <code>construct</code> method has returned.
*/
public void finished()
{
}
/**
* A new method that interrupts the worker thread. Call this method
* to force the worker to stop what it's doing.
*/
public void interrupt()
{
Thread t = threadVar.get();
if (t != null)
{
t.interrupt();
}
threadVar.clear();
}
/**
* Return the value created by the <code>construct</code> method.
* Returns null if either the constructing thread or the current
* thread was interrupted before a value was produced.
*
* #return the value created by the <code>construct</code> method
*/
public Object get()
{
while (true)
{
Thread t = threadVar.get();
if (t == null)
{
return getValue();
}
try
{
t.join();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt(); // propagate
return null;
}
}
}
/**
* Start a thread that will call the <code>construct</code> method
* and then exit.
*/
public SwingWorker()
{
final Runnable doFinished = new Runnable()
{
public void run()
{
finished();
}
};
Runnable doConstruct = new Runnable()
{
public void run()
{
try
{
setValue(construct());
}
finally
{
threadVar.clear();
}
SwingUtilities.invokeLater(doFinished);
}
};
Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
}
/**
* Start the worker thread.
*/
public void start()
{
Thread t = threadVar.get();
if (t != null)
{
t.start();
}
}
}
Then add your logic inside:
SwingWorker worker = new SwingWorker() {
#Override
public Object construct() {
// add your code here
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
// and so on...
return 0;
}
};
worker.start();
So the end resuld should look like this (Note that this is untested code):
kazananiBelirleButon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingWorker worker = new SwingWorker() {
#Override
public Object construct() {
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
try {
HashMap<String, Object> randoms = randSonuc.generateSignedIntegers(5, 0, 10);
System.out.println(randoms.toString());
String test = randoms.toString().substring(randoms.toString().indexOf("{r")+1, randoms.toString().indexOf(", da")).replace("random=", "{\"random\":") + "}";
System.out.println(tarihiYazdir(test,14));
cekilisTarihiTextPane.setText(tarihiYazdir(test,2).toString());
sonucPane.setText("\n"+sonuclariYazdir(test,0));
} catch (RandomOrgSendTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgKeyNotRunningError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientRequestsError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgInsufficientBitsError e1) {
System.out.print("lol");
e1.printStackTrace();
} catch (RandomOrgBadHTTPResponseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgRANDOMORGError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RandomOrgJSONRPCError e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return 0;
}
};
worker.start();
});
Related
Below is the code sample: Thread is getting hanged after consuming 5 or 6 values
I do not know where i am missing anything.And one more doubt that i Had was regarding calling the constructor of the MyIncrementor class. Initially I was trying to call the get and set in Producer and Consumer Class by creating new object of the MyIncrementor class, it was not working too
/**
*
*/
package multithreadingDemo;
/**
* #author Aquib
*
*/
public class ThreadCommDemo {
/**
* #param args
* #throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
MyIncrementor mi=new MyIncrementor();
Producer1 p=new Producer1(mi);
Consumerrs c=new Consumerrs(mi);
Thread t1=new Thread(p);
Thread t2=new Thread(c);
t1.start();
t2.start();
}
}
class MyIncrementor {
int myCount;
boolean valueSet;
/**
* #return the myCount
*/
public synchronized int getMyCount() {
if (!valueSet) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("get" + myCount);
valueSet = true;
notifyAll();
return myCount;
}
/**
* #param myCount
* the myCount to set
*/
public synchronized void setMyCount(int myCount) {
if (valueSet) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Set" + myCount);
this.myCount = myCount;
valueSet = false;
notifyAll();
}
}
class Producer1 implements Runnable {
MyIncrementor mi;
public Producer1(MyIncrementor mi) {
// TODO Auto-generated constructor stub
this.mi=mi;
}
public void run() {
for (int i = 1; i < 10; i++) {
mi.setMyCount(i);
System.out.println("Produced" + mi.myCount);
try
{
Thread.currentThread().sleep((int)(Math.random() * 100));
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
class Consumerrs implements Runnable {
MyIncrementor mi;
public Consumerrs(MyIncrementor mi) {
// TODO Auto-generated constructor stub
this.mi=mi;
}
public void run() {
for (int i = 1; i < 10; i++) {
int val = mi.getMyCount();
System.out.println("Consumed" + val);
}
}
}
The first thing that stands out is the lack of a while.
if (valueSet) { // <-- if is wrong
try {
wait();
wait should be in a while. This ensures that the condition is met, rather than waking up for some other reason or no reason at all.
while (valueSet) {
try {
wait();
Presumably the problem is that you have your flag the wrong way around.
if (!valueSet) {
// ...
}
// ...
valueSet = true;
Presumably the if (should be a while) is intended that valueSet is true, but then you overwrite true with true rather than modifying the variable.
Also of not, Thread.sleep is a static method. It is incredibly misleading (though a common mistake) to call it on an instance.
Thread.currentThread().sleep(/* ... */); // misleading
should be
Thread.sleep(/* ... */);
You just have logical mistakes in your MyIncrementor class, you are setting valueSet incorrectly, so you have to either change your conditions or set the flag vice versa in getMyCount and setMyCount methods.
So, here is the corrected version of MyIncrementor:
class MyIncrementor {
int myCount;
boolean valueSet = false; //line changed - just to show that by default it is initialized to false
/**
* #return the myCount
*/
public synchronized int getMyCount() {
while (!valueSet) { //corrected as advised in comments, see #Tom Hawtin - tackline answer for details
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("get" + myCount);
valueSet = false; //line changed - after getting the value set flag to false
notifyAll();
return myCount;
}
/**
* #param myCount
* the myCount to set
*/
public synchronized void setMyCount(int myCount) {
while (valueSet) { //corrected as advised in comments, see #Tom Hawtin - tackline answer for details
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Set" + myCount);
this.myCount = myCount;
valueSet = true; //line changed - after setting the value set flag to true
notifyAll();
}
}
I'm trying to get a thread to run for a swing application on button click, but the value isn't updating.
It supposed to grab the computer name I'm searching, but in order for the value to update I have to launch a new instance of the GUI.
I created a thread, but for some reason it's not working. Any help is appreciated.
(t.start is at end of code block)
searchComputerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread t = new Thread("my non EDT thread") {
public void run() {
//my work
testLabel.setText(CN);
}
};
String line;
BufferedWriter bw = null;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// String lineToRemove = "OU=Workstations";
String s = null;
Process p = null;
/*
* try { // p = Runtime.getRuntime().exec(
* "cmd /c start c:\\computerQuery.bat computerName"); } catch
* (IOException e1) { // TODO Auto-generated catch block
* e1.printStackTrace(); }
*/
try {
p = Runtime.getRuntime().exec("c:\\computerQuery.bat");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StringBuffer sbuffer = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(p
.getInputStream()));
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
// textArea.append(line);
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(
ldapName.size() - 1).getValue();
}
ComputerQuery.sendParam();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvalidNameException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally
{
try {
fw.close();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ComputerQuery.sendParam();
t.start();
}
});
UPDATE
private void threadStart() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
testLabel.setText(CN);
}
});
And I put the method here
JButton searchComputerButton = new JButton("Search");
searchComputerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
threadStart();
String line;
Be aware of the Swing Thread https://docs.oracle.com/javase/tutorial/uiswin/concurrency/
Have a look here:
http://www.javamex.com/tutorials/threads/invokelater.shtml
You must enqueue your JLabel update method invocation using the Method
SwingUtilities.invokeLater(???).
Following example does it
Further more i think that is has something to do with the .batch file invocations. Have a look here: How do I run a batch file from my Java Application?
Runnable task = new UpdateJob("Query: " + i);
SwingUtilities.invokeLater(task);
To make it more understandable.
Swing manages all draw-Operations, within one Thread.
It provides a queue. If you call a method from outside of that queue the behaviour is completely unpredictable.. NullPointer... RuntimeExc....
But if you call SwingUtilities.invokeLater(...) your method will be enqueued into the Swing-Queue and invoked as soon as possible!
UPDATE due to comment:
check your mainthread (GUI)
check your threads.
when a sub-thread (e.g a ActionListener) want to call JLabel::setText
it has to use the method SwingUtils::InvokeLater("...");
That means invokeLater() has to be call within all threads which not directly belong to the main threads.
UPDATE due to Question
In my oppinion you current't code doesn't need SwingUtilities.invok.. at all.
Did you change the Code assigned to you your question.
This question already has answers here:
Java InputStream blocking read
(7 answers)
Closed 8 years ago.
I have written a sample program to illustrate the working with pipe is thread. I have created 2 threads.
Thread1 is sending "Hi this is thread1" and call wait() for thread 2 to complete.
Thread2 is printing the message sent by thread1 and also will also append into a string buffer, then once the entire message is received, thread2 will print the contents of string buffer and will call notify. Now after calling wait() and notify both threads tend to be in deadlock
Strangely, thread2 prints the message one but does not print the contents of string buffer.
package com.tuto.MultiThreading;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipeExample {
public static void main(String[] args) throws IOException, InterruptedException {
final Object obj=new Object();
final PipedOutputStream pipeoutstream=new PipedOutputStream ();
final PipedInputStream pipeinputstream=new PipedInputStream(pipeoutstream);
Thread thread1= new Thread(new Runnable()
{
public void run() {
try {
pipeoutstream.write("Hello I am thread1".getBytes());
synchronized (obj)
{
obj.wait();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
pipeoutstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
public void run() {
try {
int data = pipeinputstream.read();
StringBuffer sb=new StringBuffer();
while(data != -1){
System.out.print((char) data);
sb.append((char)data);
data = pipeinputstream.read();
}
System.out.println();
System.out.println(sb.toString());
synchronized (obj) {
obj.notify();
}
} catch (IOException e) {
e.printStackTrace();
}
finally
{
try {
pipeinputstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.exit(1);
}
}
OUTPUT::
Hello I am thread1
Updated Resolution:
package com.tuto.MultiThreading;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipeExample {
public static void main(String[] args) throws IOException, InterruptedException {
final Object obj=new Object();
final PipedOutputStream pipeoutstream=new PipedOutputStream ();
final PipedInputStream pipeinputstream=new PipedInputStream(pipeoutstream);
Thread thread1= new Thread(new Runnable()
{
public void run() {
try {
pipeoutstream.write("Hello I am thread1".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
pipeoutstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (obj)
{
try {
obj.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
public void run() {
try {
int data = pipeinputstream.read();
StringBuffer sb=new StringBuffer();
while(data != -1){
System.out.print((char) data);
sb.append((char)data);
data = pipeinputstream.read();
}
System.out.println();
System.out.println(sb.toString());
synchronized (obj) {
obj.notify();
}
} catch (IOException e) {
e.printStackTrace();
}
finally
{
try {
pipeinputstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.exit(1);
}
}
Now i am a bit more confused. I just moved wait() from try catch to finally. How did it affect the blocking of Pipestream?
The problem is that
data = pipeinputstream.read();
in thread 2 is a blocking call. From the javadoc of PipedInputStream#read()
This method blocks until input data is available, the end of the
stream is detected, or an exception is thrown.
Thread 2 keeps waiting until one of those things happen. Since none of them will ever happen, the thread will not be able to notify the other.
This is not deadlock.
Note that even if that call unblocked and returned -1, thread 2 could still execute its notify before your thread 1 called wait. In which case, thread 1 would be a in a constant waiting state and your program would not terminate.
I have an API that I use to retrieve daily schedules on the live cable-tv for various channels. I have a scenario in which I need a guidance as to which approach should work here.
Lets say I need schedules for 10 different channels from the API.
Should I execute 10 different async tasks for the retrieval of the required data?
Problem:
How would I collect the data in an arraylist and return it once all execution is completed?
How will I access the arraylist in my main function once onpostexecute returns the result?
Or I should just provide the list of channels to my single async task and make it build a single output of arraylist for my main function invoking it?
Problem:
Since I will be accessing a webservice for this purpose, will it make it run slow as compared to my 1st approach?
Second problem with this approach is the same as I am having with my 1st one, I need to know when and how to get the complete resultset once the execution of the task is completed?
Here is some code to explain the problem:
//going with the first approach
//invoking my asynctask from an activity or another class
//I need a global arraylist which I can use after postexecute returns its result
ArrayList<String> channels = channelManager.getAllChannelsByRegion("xyz");
final ArrayList<ChannelSchedule> schedules = new ArrayList<ChannelSchedule>();
final ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
for (int i = 0; i < channels.size(); ++i){
AsyncInvokeURLTask task = null;
try {
task = new AsyncInvokeURLTask(
channels.get(i), context, new AsyncInvokeURLTask.OnPostExecuteListener() {
#Override
public void onPostExecute(String result) {
// TODO Auto-generated method stub
try {
//Need to add results to arraylist here...But cannot know when it ends completely
ChannelSchedule schedule = mapper.readValue(result, ChannelSchedule.class);
Log.v("channel name", schedule.getChannelName());
Log.v("channel date", schedule.getDate());
Log.v("channel thumb", schedule.getListOfShows().get(0).getShowThumb());
Log.v("channel time", schedule.getListOfShows().get(0).getShowTime());
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
task.execute();
}
Please let me know if something is not clear or missing.
Launching 10 AsyncTask is perfectly fine.
You can keep a count of the number of pending requests. As OnPostExecute is run on the UI thread there are no risks of race condition.
private int numberOfPendingRequests;
public void MyFunc() {
ArrayList<String> channels = channelManager.getAllChannelsByRegion("xyz");
final ArrayList<ChannelSchedule> schedules = new ArrayList<ChannelSchedule>();
final ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
numberOfPendingRequests = channels.size();
for (int i = 0; i < channels.size(); ++i) {
schedules.add(null);
}
for (int i = 0; i < channels.size(); ++i) {
AsyncInvokeURLTask task = null;
final int index = i; // final so it can be used in the onPostExecute.
try {
task = new AsyncInvokeURLTask(
channels.get(i), context, new AsyncInvokeURLTask.OnPostExecuteListener() {
#Override public void onPostExecute(String result) {
try {
ChannelSchedule schedule = mapper.readValue(result, ChannelSchedule.class);
Log.v("channel name", schedule.getChannelName());
Log.v("channel date", schedule.getDate());
Log.v("channel thumb", schedule.getListOfShows().get(0).getShowThumb());
Log.v("channel time", schedule.getListOfShows().get(0).getShowTime());
schedules.set(index, schedule);
numberOfPendingRequests--;
if (numberOfPendingRequests == 0) {
// Everything is received, do stuff here.
}
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
task.execute();
}
}
I have implemented a Steaming API for twitter. I get the streams perfectly. However, My program never ends. I have tried many combinations but can't figure out why. I am suing Apache AsyncHttpClient in java. My goal is to start the stream for example for 10 seconds, get the streams, and gracefully close the stream and exit the application (I am expecting this to happen when my Main method ends naturally). This is the code below:
public static void main(String[] args) throws Exception
{
TwitterStreamingHttpClient client = new TwitterStreamingHttpClient();
Executor ex = Executors.newSingleThreadExecutor();
ex.execute(client);
Thread.sleep(5000);
client.ceaseStream();
LOG.debug("Keeps running");
}
and this:
public class TwitterStreamingHttpClient extends DefaultHttpAsyncClient implements Runnable
{
private final static Logger LOG = LoggerFactory.getLogger(TwitterStreamingHttpClient.class);
/**
* #throws IOReactorException
*/
public TwitterStreamingHttpClient() throws IOReactorException
{
super();
// TODO: parametrize it, load from config file, spring config file?
this.getCredentialsProvider().setCredentials(new AuthScope("stream.twitter.com", 80),
new UsernamePasswordCredentials("username", "password"));
this.start();
}
public void initiateStream() throws UnsupportedEncodingException, InterruptedException, ExecutionException
{
String requestContent = new String();
requestContent = "track=NothingFeelsBetterThan";
Future future = this.execute(HttpAsyncMethods.createPost(
"https://stream.twitter.com/1.1/statuses/filter.json", requestContent,
ContentType.APPLICATION_FORM_URLENCODED), new TwitConsumer(), null);
Boolean result = future.get();
if(result==null)
{
LOG.error("Requested to close stream!");
return;
}
}
public void ceaseStream()
{
try
{
this.shutdown();
LOG.info("Shutting down the stream");
}
catch (InterruptedException e)
{
LOG.debug("InterruptedException {}", e);
}
}
/*
* (non-Javadoc)
*
* #see java.lang.Runnable#run()
*/
public void run()
{
Thread.currentThread().setName("initiateSTream Thread");
try
{
initiateStream();
Thread.currentThread().interrupt();
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ExecutionException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I tried to add a return whereever I though it mightbe helpful. but no luck. Can someone help me with this?
Edit 1: When I use the debug mode, I can see that the "initiateSTream Thread" thread. is still running while the main thread is gone!
Edit 2 (Solution): In the main method, I replaced:
Executor ex = Executors.newSingleThreadExecutor();
ex.execute(client);
with:
Thread thread = new Thread(client);
thread.start();
Now my programs ends after the designated time of streaming. But why? What is the difference between the two approaches?!