File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on multithreading from Sierra/Bates Chapter 9, Question 16

 
Sandra Bachan
Ranch Hand
Posts: 434
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sierra/Bates Chapter 9, question 16:



Even though the code compiles, it gives the following run-time error:


Exception in thread "Thread-0" java.lang.NullPointerException
at ChicksYack.run(ChicksYack.java:20)
at java.lang.Thread.run(Unknown Source)
Exception in thread "Thread-1" java.lang.NullPointerException
at ChicksYack.run(ChicksYack.java:20)
at java.lang.Thread.run(Unknown Source)


Explaination is that c should be assigned to an object. Isn't c already assigned to an object in go() on line 15?

 
Neha Daga
Ranch Hand
Posts: 504
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, but its initialised inside a method which means its limited to that method only.
 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


the code will compile because at compile time compiler is not able to find any errro.............

but as object are created at runtime..........so when JVM reaches
c.yack(Thread.currentThread().getId());
JVM not able to find any object to which "c" refers to.........
although you have done c = new Chicks();
within a go() method....but it will remain within a go method only......
but if you make
Chick c; as " static Chick c;" then below code will compile...................

or if you do c = new Chicks(); within a run() method then it will also compile.............
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What about the ChicksYack object in the line 16 and 17? Do they have not null c object?
 
Sandra Bachan
Ranch Hand
Posts: 434
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now I understand - the concept of multithreading must have overshadowed the simple concept of scope. Below is the corrected code:


 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yeah you got it...........
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic