package StatTrader;
import java.util.*;
/**
*
* @author grahamgiller
* @website http://blog.gillerinvestments.com
*
* to use this code instantiate an object
* TweetQueue twitter = new TweetQueue();
*
* and then start a worker thread
* Thread worker = new Thread(twitter);
* worker.start();
*
* finally tweet
* twitter.Update("Status");
*
* when you're done, tell the worker to stop
* twitter.Stop();
*
* that's it!
*/
public class TweetQueue implements Runnable {
protected final Tweet _tweet;
protected final List<String> _queue = Collections.synchronizedList(new ArrayList<String>());
private boolean _runnable = true;
protected String _work[] = null;
// call this constructor to use the default consumer and token keys and secrets
public TweetQueue() throws Exception {
_tweet = new Tweet();
}
// call this constructor if you have user token keys and secrets
public TweetQueue(final String tokenKey_,final String tokenSecret_) throws Exception {
_tweet = new Tweet(tokenKey_,tokenSecret_);
}
// call this constructor to specify everything
public TweetQueue(final String consumerKey_,final String consumerSecret_,final String tokenKey_,final String tokenSecret_) throws Exception {
_tweet = new Tweet(consumerKey_,consumerSecret_,tokenKey_,tokenSecret_);
}
// tweet -- this adds a status update to the queue in a thread safe manner
public void Update(final String status_) throws Exception {
if (_runnable) {
synchronized (_queue) {
_queue.add(status_);
}
}
else {
throw new Exception("Queue is stopped.");
}
}
// tell the worker thread to exit
public void Stop() {
_runnable=false;
}
// run by the worker thread
@Override public void run() {
// if we are running
while (_runnable) {
_work=null;
// copy the queue in a thread safe manner
synchronized (_queue) {
if (_queue.size()>0) {
_work=new String[_queue.size()];
_work=_queue.toArray(_work);
_queue.clear();
}
}
// examine the copy
if (_work!=null) {
// if the queue is not empty then process it
for (int i=0;i<_work.length;++i) {
try {
_tweet.Update(_work[i]);
}
catch (Exception x) {
x.printStackTrace(System.err);
}
}
}
else {
// otherwise sleep for 1 ms
try {
Thread.sleep(1L);
}
catch (Exception x) {
x.printStackTrace(System.err);
}
}
}
}
}