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.
Related
public class Test15_DeadLockUsingJoinMethod {
public static void main(String[] args) throws InterruptedException {
JoinThread1 jt1=new JoinThread1(jt2);
JoinThread2 jt2=new JoinThread2(jt1);
jt1.start();
jt2.start();
}
}
class JoinThread1 extends Thread {
JoinThread2 jt2;
public JoinThread1(JoinThread2 jt2) {
this.jt2=jt2;
}
public void run() {
System.out.println("1st thread execution start");
try {
jt2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1st thread execution stopped");
}
}
class JoinThread2 extends Thread {
JoinThread1 jt1;
public JoinThread2(JoinThread1 jt1) {
this.jt1=jt1;
}
public void run() {
System.out.println("2nd thread execution start");
try {
jt1.join();
} catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("2nd thread execution stopped");
}
}
Here I want to see the deadlock condition using only join() method. I know the deadlock code using synchronized keyword. But how can we execute deadlock condition using join method?
Your code doesn´t compile, you are using jt2 in the constructor of jt1, before it is defined.
In order to get a deadlock, you should define a new constructor for JoinThread1 that do not have any parameter. So, you first define jt1 using the new constructor. Then you define jt2 passing through parameter jt1 (like you have now). Then you should define a setter for the other thread in JoinThread1.
Example:
New constructor
public JoinThread1() {
}
Setter method
public void setThread(JoinThread2 jt2){
this.jt2 = jt2;
}
Main
public static void main(String[] args) throws InterruptedException {
JoinThread1 jt1=new JoinThread1();
JoinThread2 jt2=new JoinThread2(jt1);
jt1.setThread(jt2);
jt1.start();
jt2.start();
}
After that changes,you will get a deadlock.
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();
}
}
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.
class firstThread extends Helper1
{
Thread thread_1 = new Thread(new Runnable()
{
#Override
public void run() {
try {
for (int i = 1; i <= 20; i++) {
System.out.println("Hello World");
Thread.sleep(500);
if (i == 10) {
Notify();
Wait();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
class secondThread extends firstThread
{
Thread thread_2 = new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try {
Wait();
for(int i = 1; i<=20; i++)
{
System.out.println("Welcome");
Thread.sleep(100);
}
Notify();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
class Helper1
{
public synchronized void Wait() throws InterruptedException
{
wait();
}
public synchronized void Notify() throws InterruptedException
{
notify();
}
}
public class InheritanceClass {
public static void main(String[] args)
{
Thread f = new Thread(new firstThread().thread_1);
Thread s = new Thread(new secondThread().thread_2);
f.start();
s.start();
}
}
Only the first Thread has an output. Please try my code. I don't know why it happens.
The second thread does not give output, I suppose it's because of Wait() in the secondThread, I don't know what to do.
The problem is with the following code:
class Helper1
{
public synchronized void Wait() throws InterruptedException
{
wait();
}
public synchronized void Notify() throws InterruptedException
{
notify();
}
}
Above, the wait() and notify() calls are equivalent to this.wait() and this.notify(). However, thread1 and thread2 are separate objects so they are not ever going to communicate via this method.
In order for communication to occur, you need a shared lock object. For example:
Object lock = new Object();
firstThread = new firstThread(lock);
secondThread = new secondThread(lock);
and synchronizations like:
void wait(Object lock) {
synchronized(lock) {
lock.wait();
}
}
void notify(Object lock) {
synchronized(lock) {
lock.notify();
}
}
Disclaimer: I would never do this personally, however it does answer the OP's question.
This code is really confusing, which is making it hard to see the underlying problem.
You should never start a class with a lower-case letter since it makes it look like a method/field name (e.g. firstThread).
I'm pretty sure Wait and Notify have no reason to be synchronized.
Why does secondThread inherit from firstThread??? Actually, why do you have those two classes at all? You should just make an anonymous inner class from Helper1 or something.
Anyway, the problem is that when you call Notify() in thread1 it notifies itself, not thread2.
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();
}