Why the c object null in run method? - java

I am solving the below interview question. It's throwing a NullPointerException, but I do not understand how the value of c is null. I already initialized it in the go() method.
package swain.javainterviewhub.blogspot.in;
class Chicks{
synchronized void yack(long id){
for(int x=1;x<3;x++){
System.out.println(id+" ");
Thread.yield();
}
}
}
public class JavaInterviewHub implements Runnable {
Chicks c;
public static void main(String[] args) {
new JavaInterviewHub().go();
}
void go(){
c=new Chicks();
new Thread(new JavaInterviewHub()).start();
new Thread(new JavaInterviewHub()).start();
}
#Override
public void run() {
c.yack(Thread.currentThread().getId());
}
}
Console:
Exception in thread "Thread-0" Exception in thread "Thread-1" java.lang.NullPointerException
at swain.javainterviewhub.blogspot.in.JavaInterviewHub.run(JavaInterviewHub.java:28)
at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
at swain.javainterviewhub.blogspot.in.JavaInterviewHub.run(JavaInterviewHub.java:28)
at java.lang.Thread.run(Unknown Source)

Since Chicks.yack() is synchronized, you probably meant for both threads to use the same instance of Chicks, which means you probably meant for both threads to use the same instance of JavaInterviewHub, in which case you probably meant to start both threads with the instance that was created in main().
If that's all true, then you need to use this when creating the threads:
void go(){
c=new Chicks();
new Thread(this).start();
new Thread(this).start();
}
As for the question of when to create an instance of Chicks, and therefore assign a value to c, you have 3 choices:
Leave the code as-is. A bit obscure, but valid.
Do it in a constructor.
Do it when declaring c. Easiest.
Option 2: Constructor
private JavaInterviewHub() {
this.c = new Chicks();
}
Option 3: Declaration
private final Chicks c = new Chicks();

When you create a thread like this:
new Thread(new JavaInterviewHub()).start();
A new instance of JavaInterviewHub is created. In this instance c is not set anywhere, so when the run method is executed, a NullPointerException is thrown.
One way to solve the issue is to initialize c in JavaInterviewHub's constructor. Another would be to initialize c where it's declared. See the acepted answer for more information.

Related

Java tracing confusion

Can someone help me to understand why java is trying to make an instance of a before b. And also, why it is looping between line 2 and line 3?
public class Winterfell {
private Winterfell a= new Winterfell();
public Winterfell() throws Exception {
throw new Exception("Fire and Ice");
}
public static void main(String[] args) {
try {
Winterfell b = new Winterfell();
System.out.println("Surprise!");
} catch (Exception ex) {
System.out.println("I told you so");
}
}
}
This will cause a StackOverflowError.
By having a field referencing a new object of the same class or by making a new object of the same class in the constructor you have an infinite number of calls to create a new Winterfell object.
That is why it is looping.
To fix this you likely want to remove private Winterfell a= new Winterfell(); so that a single Winterfell object is created.
private Winterfell a= new Winterfell();
Is invoked prior to invoking the constructor of Winterfell because it's a data member. Check out the Oracle documentation for object construction for more info.

what is the difference between the two structures of creating threads mentioned below [duplicate]

This question already has answers here:
"implements Runnable" vs "extends Thread" in Java
(42 answers)
Closed 7 years ago.
Struture 1 :
public class Runner {
public static void main(String[] args) {
Thread t1 = new Thread(new Thread(){
public void run() {
System.out.println("value :");
}
});
t1.start();
}
}
Structure 2 :
public class Runner {
public static void main(String[] args) {
Thread t1 = new Thread(){
public void run(){
System.out.println("value :");
}
};
t1.start();
}
}
Result in both the cases is same.
What is the difference between the two above mentioned structres? Please explain.
You are executing thread using inner class in your first example. So basically you are passing object of one thread to another thread in your first example.
start() method always looks for run method. And t1.start() running there thread in both the example.
In the first example you provide the Thread with a Thread in the constructor. Its weird, and it works because Thread implements Runnable, but the usage of it like this is discouraged. Just use Runnable in the constructor
By default, Thread's run() method just runs the Runnable given to the constructor. If you don't provide a Runnable, and neither override the run method of the Thread, then it will basically execute no code.
The decompiled run method of my Thread class looks like this:
public void run() {
if(this.target != null) {
this.target.run();
}
}

How to access a method from another running thread in java

I am new to Java Threads. What I am trying to do is from ThreadB object gain access to the instance of a current running thread, ThreadA, and call its method called setSomething.
1) I think I am making harder than it really is
2) I have a null pointer exception so I must be doing something wrong when accessing that method
Here is what I have so far and I have done my due diligence and looked here on StackOverflow for a similar question.
I have a current Thread running in the background:
// assume this thread is called by some other application
public class ThreadA implements Runnable{
private Thread aThread;
public ThreadA(){
aThread = new Thread(this);
aThread.setName("AThread");
aThread.start();
}
#Override
public void run(){
while(true){
// doing something
}
}
public void setSomething(String status){
// process something
}
}
// assume this thread is started by another application
public class ThreadB implements Runnable{
#Override
public void run(){
passAValue("New");
}
public void passAValue(String status){
// What I am trying to do is to get the instance of ThreadA and call
// its method setSomething but I am probably making it harder on myself
// not fully understanding threads
Method[] methods = null;
// get all current running threads and find the thread i want
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for(Thread t : threadSet){
if(t.getName().equals("AThread")){
methods = t.getClass().getMethods();
}
}
//**How do I access ThreadA's method, setSomething**
}
}
Thank you in advance
Allen
Wow why do you make things to much complex?! this is not as hard as you think (killing a dragon in a dark castle!)
okay all you need to do is passing the threadA references to threadB! just this. and let me say that when you call a method from thread b, so it runs by thread b, not the class has been hosted.
class ThreadA implements Runnable {
public void run() {
//do something
}
public void setSomething() { }
}
class ThreadB implements Runnable {
private ThreadA aref;
public ThreadB(ThreadA ref) { aref = ref; }
public void run() {
aref.setSomething(); // Calling setSomething() with this thread! (not thread a)
}
}
class Foo {
public static void main(String...arg) {
ThreadA a = new ThreadA();
new Thread(a).start();
ThreadB b = new ThreadB(a);
new Thread(b).start();
}
}
and here a simple threadtutorial
When or after you instantiate your ThreadB object, give it a reference to your ThreadA object instance. Something like:
ThreadA a = new ThreadA();
ThreadB b = new ThreadB(a);
Then, within the ThreadB code, you can just invoke ThreadA's method by using the reference you have no doubt stored in an instance variable in ThreadB.

Starting Threads In A Constructor

It is said threads should NEVER be started in constructors, but I am not sure how this reference escapes the Test constructor in this case. I looked at the underlying Thread.java and I cannot figure this out.
class Test {
static MyThread thread;
public Test() {
thread = new MyThread();
thread.start();
}
}
class MyThread extends Thread {
public void run() {
//do stuff
}
}
Thanks for the help.
thread = new MyThread(); would call Thread super constructor:
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
I do not see a reference getting away.
this can only escape if the thread references this (eg, if it's an inner class)
Your thread does not reference this, so this is not an issue.
However, constructing an object is generally expected to be side-effect-free; this is not a good idea.

How locks obtained in multithreading and on which object?

Class ThreadTest extends Thread {
public synchronized void run() {
}
public static void main(String args[])
{
Thread t1=new ThreadTest();
Thread t2=new ThreadTest();
t1.start();
t2.start();
}
}
I want to know in above scenario, how locks obtained and on which object?
Does above scenario valid?
As locks are obtained on a calling object in method synchronisation then in above scenario on which object lock will be obtained. One more question who(or which object) invokes the run method?
Thanks,
-Abhishek
t1 has the lock of the t1 instance.
t2 has the lock of the t2 instance.
But your example doesnt make much sense..
Maybe this example will help you:
public class Test extends Thread {
private String name;
public Test(String name) {
this.name = name;
}
public synchronized void run() {
System.out.println(name);
while(true)
{
// loop endless
}
}
public static void main(String args[])
{
Thread t1= new Test("t1");
Thread t2= new Test("t2");
t1.start();
t2.start();
}
}
The output is:
t1
t2
You have started both the threads, but it depends on JVM which thread it might execute, so depending upon the thread which starts executing will acquire the lock first and the second thread cant be on running state till the first thread stops.
but in your case as both are different thread instances they run parallel, as the lock is acquired at the object level.
Your example doesn't make that much sense, because locks are on a per-instance level, not on a per-class level as you might wanted to use them.
I think you got it wrong a bit. The thread is wrapping up the code that is executing commands. These executions often contain access on other objects. That is the point, where locking comes into the game. Each of these objects have a monitor that can be obtained by threads. However, only one thread can obtain the lock at a time. Thus, other threads are enqueued and can access object as soon as the current holder releases it, trivially by exiting a synchronized code block.
I think you might wanted to do something like this:
class ThreadTest extends Thread
{
private final Foo f;
public ThreadTest(Foo f,int i)
{
super(""+i);
this.f = f;
}
#Override
public void run()
{
f.bar();
}
public static void main(String args[])
{
Foo f = new Foo();
Thread t1 = new ThreadTest(f,1);
Thread t2 = new ThreadTest(f,2);
t1.start();
t2.start();
}
public static class Foo
{
public synchronized void bar()
{
System.out.print("hello form Thread ");
System.out.println(Thread.currentThread().getName());
}
}
}
Formal Definition
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
If what you want is to have only one thread execute at a time (What's the point) then you should call a static method and call that from inside your run(), there is only one static method for all object of a class
How do synchronized static methods work in Java?

Categories