Runnable does not run inside Callable - java

In the following code I create a callable which creates a Runnable inside the call()-method. My problem is that run()-method is never reached (code does not get executed). Do you know why and how to fix that?
public static void main(String[] args) {
Callable<Object> c = new Callable<Object>() {
#Override
public Object call() throws Exception {
Runnable r = new Runnable() {
#Override
public void run() {
System.out.println("hi");
}
};
return null;
}
};
try {
c.call();
} catch (Exception e) {
}
}

Callable<Object> c = new Callable<Object>() {
#Override
public Object call() throws Exception {
Runnable r = new Runnable() {
#Override
public void run() {
System.out.println("hi");
}
};
r.run();
return null;
}
};
try {
c.call();
} catch (Exception e) {
}

Do you know why...
Already explained by others: You have written code that creates a Runnable instance, but your code does not do anything with the instance after creating it. Your code does not directly call the run() method, nor does your code hand the instance off to any other object that would call the method.
...and how to fix that?
That would depend on what you want the code to do. There are simpler ways to write a program that prints "hi" if that's all you want.
It looks as if you are trying to learn something, but you haven't told us what you want to learn.

Related

start() is not starting a thread

I have written below sample code to test behavior of threads . But main is not starting thread test1 execution , Please let me know what is the problem with this code
class test1 implements Runnable
{
Thread t ;
test1(String Name)
{
t = new Thread(Name);
t.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Entered test1 run");
}
}
public class SampleThread{
public static void main(String[] args) {
Thread r = Thread.currentThread();
System.out.println(r.getName()+" "+r.getPriority());
r.setName("MainThread");
r.setPriority(8);
test1 t1 = new test1("test1");
System.out.println("calling threads");
try
{
t1.t.join();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Changing t = new Thread(Name); to t = new Thread(this, Name); (in test1) would make your code work.
But still your code it quite confusing. You can make a java thread by sub-classing Thread or implementing Runnable and passing the runnable to a thread, and you seem to trying to do both at the same time (incorrectly).
I suggest you look up a guide on threads like https://www.tutorialspoint.com/java/java_multithreading.htm

How to wait for callback before leaving method (Java)

I have a method in which I call another method that has a callback. I want to receive this callback before leaving my method. I saw some other posts in which latches are used. My code looks like this:
public void requestSecurityToken(<some params>){
final CountDownLatch latch = new CountDownLatch(1);
MyFunction.execute(<someParams>, new RequestListener<Login>() {
#Override
public void onRequestFailure(SpiceException spiceException) {
//TODO
}
#Override
public void onRequestSuccess(Login login) {
//handle some other stuff
latch.countDown();
}
});
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
This doesn't work, the method is stuck in the await() function. What happens is that, the method immediately jumps to the await(), and doesn't go into the onRequestSuccess() or onRequestFailure() method again. I guess this is a concurency problem... Any ideas on how to fix this issue?
EDIT: Added the line of code where I create the latch.
When you are doing this
new RequestListener<Login>
You are passing an object to your function , which implements an interface.
That is why those methods are not getting called , those methods are called only when you get the request result (success or failure).
You can do this instead.
MyFunction.execute(<someParams>, new RequestListener<Login>() {
#Override
public void onRequestFailure(SpiceException spiceException) {
someFunction();
}
#Override
public void onRequestSuccess(Login login) {
//handle some other stuff
someFunction();
latch.countDown();
}
});
public void someFunction()[
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Call finalize in shutdownHook could not work

In below code snippet, the finalize() method would never be called. But when I replace finalize() to close() in addShutdownHook. The finalize() method would be call. Is it a bug here?
public class Main {
public Main() {
Runtime.getRuntime().addShutdownHook(
new Thread(
new Runnable() {
public void run() {
try {
finalize();
} catch (Throwable e) {
System.out.println(e);
}
}
})
);
}
public static void main(String[] args) {
System.out.println("Enter main");
Main m = new Main();
m = new Main();
m = null;
System.out.println("Before System.exit(0);");
System.exit(0);
}
protected void finalize() {
System.out.println("Call finalize()");
}
protected void close() {
finalize();
}
}
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
try {
finalize();
} catch (Throwable e) {
System.out.println(e);
}
}
}));
This calls the finalize method of the anonymous Runnable instance (which does nothing because it is the inherited Object#finalize()), not the one defined in your class. You can call the latter using:
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
try {
Main.this.finalize();
} catch (Throwable e) {
System.out.println(e);
}
}
}));
A much better way is to rename the method to avoid overriding Object#finalize() which is called when the garbage collector detects the object is no longer referenced.
Also note that in your code, you're registering two shutdown hooks (the constructor is called twice), so the method finalize will be called twice.

Synchronizing infinitely looped service's initialization part

I'm trying to implement a piece of code to synchronously start looped service in Java. The idea is, code under // STARTER comment should be considered as piece of Service.go() method, so if service fails to start, I want to re-throw the exception synchronously. That piece of code should only finish in case I've tried to start the thread, waited until its execution flow reached some point and next, if there are no problems, my go() method quits and thread goes on, or, if there were problems, I can re-throw the exception caught in thread's run() method from my go() method. Here's the solution that seems to work fine, but I'm curious if it's possible to make it a couple times shorter :-)
public class Program {
private static boolean started;
private static Throwable throwable;
public static void main(String[] args) {
final Object startedSetterLock = new Object();
Thread thread = new Thread() {
public void run() {
System.out.printf("trying to start...\n");
boolean ok;
Throwable t = null;
try {
init();
ok = true;
} catch(Exception e) {
ok = false;
t = e;
}
synchronized(startedSetterLock) {
started = ok;
throwable = t;
startedSetterLock.notifyAll();
}
if(!ok) {
return;
}
while(true) {
try {
System.out.printf("working...\n");
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.printf("interrupted\n");
}
}
}
private void init() throws Exception { throw new Exception(); } // may throw
};
// STARTER
synchronized(startedSetterLock) {
thread.start();
try {
startedSetterLock.wait();
} catch(InterruptedException e) {
System.out.printf("interrupted\n");
}
}
// here I'm 100% sure that service has either started or failed to start
System.out.printf("service started: %b\n", started);
if(!started) {
throwable.printStackTrace();
}
}
}
And also, there's a reason to have initialization code executed within that thread, so, please, don't advise running initialization code explicitly in go() method and then just passing all the stuff to the thread.
Thanks!
How about overriding the Thread.start() method?
public static void main(String[] args) {
Thread t = new Thread() {
public void run() {
while (true) {
try {
System.out.printf("working...\n");
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.printf("interrupted\n");
}
}
}
#Override
public synchronized void start() {
try {
init();
} catch (Exception e) {
throw new RuntimeException(e);
}
super.start();
}
private void init() throws Exception {
throw new Exception("test");
}
};
t.start();
}

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