Timer function not running. Java - java

I have a question relating to the timer function. I have managed to find the cause of my problem, but I'm not sure on how to address it. I will give you an overview of my function. It will first execute the cost() function, with a background thread working. However, what I realize was that my cost() function failed to load right at the beginning. Secondly, it's program to run every 60 secs which it failed as well. I check my code for my cost() function and it works fine if I call it down without the timer function. Could it be my Opencsv() function? The question is it due to constraint of the timer function or is there ways to address this issue?
public static void main(String[] args) {
launch(EVschedulerApp.class, args);
Timer timer = new Timer();
// timer.scheduleAtFixedRate(new Cost(), 10*1000, 10*1000);
timer.scheduleAtFixedRate(new Cost() {
#Override
public void run() {
new Thread(new Runnable() {
public void run() {
File file = new File("D:/test.csv");
if(file != null){
try {
Opencsv csv = new Opencsv();
csv.Csvreader();
} catch (IOException ex) {
Logger.getLogger(EVschedulerApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
}).start();
}
Opencsv class file:
public class Opencsv {
public void Csvreader() throws IOException {
try {
// TODO code application logic here
CSVReader reader = new CSVReader(new FileReader("D:/Test.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + " " + nextLine[1]+ " " + nextLine[2]+ " " + nextLine[3]);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Opencsv.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Cost Class:
public class Cost extends TimerTask{
public void run() {
Calendar rightNow = Calendar.getInstance();
Integer hour = rightNow.get(Calendar.HOUR_OF_DAY);
if (hour==23 ) {
try {
URL tariff = new URL("http://www.******.downloadRealtime=true");
ReadableByteChannel tar = Channels.newChannel(Test.openStream());
FileOutputStream fos = new FileOutputStream("Test.csv");
fos.getChannel().transferFrom(tar, 0, 1<<24);
} catch (IOException ex) {
Logger.getLogger(Cost.class.getName()).log(Level.SEVERE, null, ex);
}
}
else {
}
}

I really think that your "bug" is not here, but somewhere else. Also you should be really looking at
ScheduledThreadPoolExecutor
instead of the Timer, it would be something like this :
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
//Do your stuff in here
}
}), 60, TimeUnit.SECONDS );
Also may I recommend not to swallow the InterruptedExceptions - there are a lot of posts here on SO on this subject.
Cheers,
Eugene.

I think your bug is that you never call Cost's run() method, you are not just overriding it, you are hiding it. Try something like this:
timer.scheduleAtFixedRate(new Cost() {
#Override
public void run() {
super.run(); //Added this call to Cost's original method.
new Thread(new Runnable() {
public void run() {
//your code still here
}
}).start();
}
Although, as others point out, you should look into the Executor Service.

It seems that your bug is in class Cost that you have not posted here.
But anyway you have yet another problem here. Why do you create yet another thread inside run() of timer task. It may have sense only if your business logic takes significant time. In your case if your csv file is very large.
Start from simple implementation. Create task that synchronously pareses CSV. Schedule it and see how is it working. If and only if you see that task takes a lot of time thing about using yet another thread. In this case take a look on Executors.

Related

In Android, I need to get data via TCP in an onDraw() method

As the title describes, I have a View class in which I need to reach out to get some data via TCP before I update the drawing. When I implemented this in my usual new Thread()...start() construction Eclipse whined at me about instantiating something new in an onDraw() method. In response to that, I reconfigured my thread as a class variable and I'm attempt to execute t.start() in the onDraw() loop.
However, there must be some thread baby-sitting I'm not aware about because my code is throwing an exception (java.lang.IllegalThreadStateException: Thread already started) when it attempts to start the thread the second time. The following is the current version of my code:
Thread t = new Thread()
{
public void run()
{
try
{
String st1 = getNetwork(); // Get network information
if (null != st1)
{
String[] st = st1.substring (st1.indexOf (' ') + 1, st1.length()).split (",+");
setNeighbors (st.length);
for (String s:st)
{
Log.e (TAG, s.trim());
String[] t1 = s.trim().split ("\\s+");
numbers.add (t1[0]);
addresses.add (t1[1]);
states.add (t1[2]);
}
}
}
catch (Exception ex)
{ }
finally
{
NetworkView.this.wait = false;
}
}
};
#Override
protected void onDraw (final Canvas canvas)
{
if (++drawCtr % 300 == 0)
{
this.wait = true;
t.start();
while (wait);
try
{
t.join();
}
catch (InterruptedException e) { }
}
update (canvas);
try { Thread.sleep (50); }
catch (InterruptedException e) { }
invalidate();
}
I get that the 2nd time around, my thread has already been started. How do I "reset" or "unstart" it for a 2nd attempt??
As Henry pointed out, my initial concept was a bad idea. A much more workable architecture was to have the TCP thread control the redraw, rather than having the redraw thread control the TCP data exchange, especially because there's no need (at least in my case) to redraw the screen between TCP updates. Hence, I implemented this thread in my View object's constructor:
(new Thread()
{
public void run()
{
while (looping)
{
try
{
// Get the important data via TCP (CAN'T be on the UI thread)
String st1 = tcpClient.getNetwork();
String st2 = tcpClient.getDiscovery();
}
catch (Exception ex)
{ }
finally
{
try
{
// Redraw the display (HAS TO be on the UI thread)
net.runOnUiThread (new Runnable()
{
#Override
public void run()
{
invalidate();
}
});
}
catch (Exception ex)
{ }
try { Thread.sleep (2000); }
catch (InterruptedException e) { }
}
}
}
}).start();
The key is the invalidate() call in the finally block (that needs to be run on the UI thread). That will update the screen based on the fresh new information.

Could not create epoll instance. errno=24

what does this runtime-error mean?
I already googled it, some say, it belongs to timers, other say its a socket error and more say, it belongs to pictures. I have sockets and timers (lot of timers) and i have no idea, which of these causes it. SOmetimes it works for over an hour, and other times just for 5 minutes. Any Ideas?
A basic impression of what this error is about is enough. If i would post all the code, where it could happen, this page would be multiple kilometres long ( a little extreme of course, but it is lot of code.)
Found right now, it could belong to too many open files but im not using any extern files in my app.
Seems to be a memory leak, belonging to this part:
public static Runnable connection() throws IOException {
Log.e("Communication", "connection");
new Thread(new Runnable() {
public void run() {
Looper.prepare();
try {
serv = new ServerSocket(port); sock = serv.accept();
reader(); } catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return null;
After deleting a part of the code above everything works fine again. Deleted the looper.prepare() and my app does not die anymore.
public static void sendJsonList(final List<String> jsonStrlist,
final String resturl) {
Thread t = new Thread() {
public void run() {
Looper.prepare();
/* Your HTTP clients code */
try {
for (String jsonStr : jsonStrlist) {
/* Loop logic */
response = client.execute(post);
if (response != null) {
/*reponse handler logic */
}
}
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop();
}
};
t.start();
}

How to pass parameter to an already running thread in java?

How to pass parameter to an already running thread in java -- not in the constructor, & probably without using wait() (possible ??)
Something similar to a comment in How can I pass a parameter to a Java Thread?
Do you mean passing a parameter to an already running thread ? Because all the current answers are about passing parameters to new threads... – Valentin Rocher May 18 '09 at 10:43
[edited]
yes, I was looking for something like the producer/consumer pattern.
I wanted something like a thread in which has the processing & is ready
for keyboard input. The other thread is just to monitor network and pass
on the received text to the processing thread.
Maybe what you really need is blocking queue.When you create the thread, you pass the blocking queue in and the thread should keep checking if there is any element in the queue. Outside the thread, you can put elements to the queue while the thread is "running". Blocking queue can prevent the thread from quit if their is nothing to do.
public class Test {
public static void main(String... args) {
final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
Thread running = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
String data = queue.take();
//handle the data
} catch (InterruptedException e) {
System.err.println("Error occurred:" + e);
}
}
}
});
running.start();
// Send data to the running thread
for (int i = 0; i < 10; i++) {
queue.offer("data " + i);
}
}
}
The "other thread" will have its own life, so you can't really communicate with it / pass parameters to it, unless it actively reads what you gives to it.
A thread which you allows you to communicate with it typically reads data from some buffered queue.
Have a look at ArrayBlockingQueue for instance, and read up on the Consumer-Producer pattern.
public class T1 implements Runnable {
//parameter of thread T1
public static AtomicBoolean flag = new AtomicBoolean();
#Override
public void run() {
}
}
public class T2 implements Runnable {
#Override
public void run() {
//parameter to an already running thread
T1.flag.set(true);
}
}
What about such way:
class TestRun implements Runnable
{
private int testInt = -1;
public void setInt(int i)
{
this.testInt = i;
}
#Override
public void run()
{
while (!isFinishing())
{
System.out.println("Working thread, int : " + testInt);
try
{
Thread.sleep(2500);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
.....
TestRun first = new TestRun();
TestRun second = new TestRun();
(new Thread(first)).start();
(new Thread(second)).start();
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
}
first.setInt(101);
second.setInt(102);

Java Thread StackOverflowError

...
Thread showWordThread = new Thread() {
public void run() {
try {
sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
this.run();
}
};
showWordThread.run();
}
...
It had run for about 5 minutes before error occured:
Exception in thread "Thread-2" java.lang.StackOverflowError.
Why?
I had tried this:
Thread showWordThread = new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
});
showWordThread.start();
But error still occured.
Others have explained that you should use a while loop instead. You're also trying to call the run method inside your anonymous class declaration. Additionally, you should call start, rather than run - when the new thread has started, it will call run automatically. I'd actually suggest implementing Runnable rather than extending Thread, too. So you want:
Thread showWordThread = new Thread(new Runnable() {
#Override public void run() {
while (someCondition) {
try {
Thread.sleep(config.delayTime * 1000);
// Presumably do something useful here...
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
});
showWordThread.start();
Alternatively, consider using a Timer or ScheduledExecutorService.
You are calling run method as recursively. Java holds call information(such as parameters) in stack memory so when you are calling a method recursively and there isn't any end point, stack memory will consumed and StackOverflow exception throws.
Maybe you want increasing Heap Size of JVM but this solution don't solve your problem and StackOverflow will occurred .
I guess you want run a thread continually. I recommend following code:
Thread showWordThread = new Thread()
{
public void run()
{
try
{
sleep(config.delayTime * 1000);
}
catch (Exception e)
{
System.out.println(e.toString());
}
// this.run(); this snnipet code make error
}
};
showWordThread.run();
}
Don't call run() from within the run() method. That'll definitely produce a stack overflow because you keep reentering the same method with no exit condition. Instead use a while loop.
Thread showWordThread = new Thread() {
public void run() {
while(condition) {
try {
sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
};
showWordThread.start();
}
Your code have infinity recursive, you should change the code to:
Thread showWordThread = new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(config.delayTime * 1000);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
};
showWordThread.start();
Your function calls itself each time you run it.
That results in a stack overflow.
Maybe because you call run method (this.run()) from itself?

Method run() is not executed

I'm using java. I'm trying to execute a thread, but the issue I'm getting is
thread.start() method is getting executed, but as we know when we call the start method of thread, the run() method gets called internally.
But in my case the run() method is not getting executed:
public static void main(String[] args) throws Exception {
parseArguments(args);
ScraperStore scraperStore = ScraperStore.getInstance();
SocialSiteManager siteManager = new SocialSiteManager();
sitesToScrape = siteManager.getSocialSitesToScrape();
for (SocialSite site : sitesToScrape) {
ScrapeThread srThread = new ScrapeThread("srThread");
Thread scraper = new Thread(srThread);
srThread.setSiteToScrape(site);
srThread.setPageTypeToScrape(startPageToScrape);
srThread.setTypeToScrape(typeToScrape);
ArrayList<String> listOfValues = ScraperStore.getNextUrlToScrape(startPageToScrape, site);
srThread.setTypeToScrape(typeToScrape);
try {
srThread.setUrlOwnedBy(listOfValues.get(0));
srThread.setStartUrl(listOfValues.get(1));
scraper.start();
boolean state = scraper.isAlive();
scrapeThreads.add(scraper);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Thread class:
class ScrapeThread {
public ScrapeThread(String threadName) {
thread = new Thread(this,threadName);
System.out.println(thread.getName());
}
}
Run method:
public void run() {
try {
System.out.println("in the run method");
selenium = new DefaultSelenium(config.getHost(), Integer.parseInt(config.getPort()),
config.getBrowser(), config.getUrl());
selenium.start();
Integer count = 0;
while (startUrl != null) {
HtmlPage homePage = new HtmlPage();
homePage.setCreatedBy(new String());
homePage.setCreatedon(new String());
homePage.setModifiedBy(new String());
homePage.setModifiedOn(new String());
homePage.setNoOfItemsFound(new String());
homePage.setOwnedBy(urlOwnedBy);
homePage.setPageType(scraper.getPageTypeToScrape());
homePage.setPageUrl(startUrl);
proxy = getInitialisedProxy();
scraper.setNavigator(proxy.getNavigator());
scraper.setStartUrl(startUrl);
try {
scraper.initialize();
} catch (MyException e) {
if (status == false){
throw new Exception(MyException.NOTFOUND);
}
}
}
}
}
I'm using sellinium. Is there any chance that I'm getting the issue because of selenium?
Look at code and compare it with your code.
public static void main(String []args)
{
Runnable inst=new Runnable()
{
public void run()
{
System.out.println("Thread statement!");
}
};
Thread thrd=new Thread(inst);
thrd.start();
}
How did you come to know run method is not executed . didu u put a trace on the run method?
//Old
new Thread(niidleThread,"scraper"); scraper.start()
// new
new Thread(srThread); or
new Thread(srThread,"scraper");
Try the new one i have given above;
Just from a cursory review of your code... I see that you might have gone a little thread-happy. Consider:
ScrapeThread srThread = new ScrapeThread("srThread"); // This is creating your ScrapeThread object (which should really implement the Runnable interface)
Thread scraper = new Thread(srThread); // This is creating a thread which wraps another thread... take this out.
srThread.setSiteToScrape(site);
srThread.setPageTypeToScrape(startPageToScrape);
srThread.setTypeToScrape(typeToScrape);
ArrayList<String> listOfValues = ScraperStore.getNextUrlToScrape(startPageToScrape, site);
srThread.setTypeToScrape(typeToScrape);
try {
srThread.setUrlOwnedBy(listOfValues.get(0));
srThread.setStartUrl(listOfValues.get(1));
scraper.start(); // You would want to replace this with srThread.start(); once fixing the items I addressed above
boolean state=scraper.isAlive();
scrapeThreads.add(scraper);
}
catch (Exception e) {
e.printStackTrace();
}
http://www.javabeginner.com/learn-java/java-threads-tutorial might help you out a bit.

Categories

Resources