Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / April 2007

Tip: Looking for answers? Try searching our database.

Null pointer exception problem

Thread view: 
Colin - 30 Mar 2007 06:43 GMT
Can someone show me why I am getting a null pointer exception from my
code.  Here is a much simplified version:

class A {
   private Vector<MyObject> foo;

   public void func1() {
       B.func2(this);
   }

   public void add(MyObject obj) {
       foo.add(obj);
   }
}

class B {
   public static void func2(A obj) {
       while (some condition) {
           MyObject myObj = new MyObject();
           obj.add(myObj);
       }
   }
}

If you are wondering, in my real program, class B parses an XML file
and creates the objects to add to A from the file.

Thanks,
Colin
SadRed - 30 Mar 2007 07:02 GMT
> Can someone show me why I am getting a null pointer exception from my
> code.  Here is a much simplified version:
[quoted text clipped - 27 lines]
> Thanks,
> Colin

We see no problem in your code.
--------------------------------------------
/* save and compile as A.java */
import java.util.*;

class A {
 private Vector<MyObject> foo;

 public A(){
   foo = new Vector<MyObject>();
 }

 public void func1() {
   B.func2(this);
 }

 public void add(MyObject obj) {
   foo.add(obj);
 }

 public static void main(String[] args){
   A aa = new A();
   aa.func1();
 }
}

class B {
 public static void func2(A obj) {
   boolean boo = true;

   while (boo) {
     MyObject myObj = new MyObject();
     obj.add(myObj);
     boo = false;
   }
 }
}

class MyObject{
}
---------------------------------------
tahseen.ur.rehman@gmail.com - 30 Mar 2007 07:11 GMT
> We see no problem in your code.
Well there is a problem :) which you fixed by initializing "foo"
vector in the constructor.
Colin - 30 Mar 2007 07:19 GMT
On Mar 30, 2:11 am, tahseen.ur.reh...@gmail.com wrote:
> > We see no problem in your code.
>
> Well there is a problem :) which you fixed by initializing "foo"
> vector in the constructor.

::smacks forehead::

Thanks :)
Lew - 30 Mar 2007 14:23 GMT
> On Mar 30, 2:11 am, tahseen.ur.reh...@gmail.com wrote:
>>> We see no problem in your code.
>> Well there is a problem :) which you fixed by initializing "foo"
>> vector in the constructor.
>
> ::smacks forehead::

I always feel queasy seeing

> Vector<MyObject>

Why did you choose Vector over other List implementations? Better alternatives
have been around since 1998.

-- Lew
Colin - 05 Apr 2007 18:47 GMT
> I always feel queasy seeing
>
[quoted text clipped - 4 lines]
>
> -- Lew

I am just starting to program in Java after years of C++, so vector
was a familiar word.  I would be very interested in learning about
other types of lists.  Do you have a link describing or comparing the
different available types?

Thanks,
Colin
Oliver Wong - 05 Apr 2007 21:15 GMT
>> Why did you choose Vector over other List implementations? Better
>> alternatives
[quoted text clipped - 4 lines]
> other types of lists.  Do you have a link describing or comparing the
> different available types?

http://java.sun.com/javase/6/docs/api/java/util/List.html

   In Java, "List" is the name of an interface which several classes
implement (see the "all known implementing classes" list). "Vector" is the
name of a class which implements the List interface.

   The basic difference between Vector and the other classes that
implement List is that historically, Vector was written before the List
interface existed. It was later retrofitted to implement that list, so you
have a lot of "duplicate" methods, like elementAt(int index) and get(int
index), the latter being part of the List API, and the former being part
of the pre-List API of Vector.

   - Oliver
Lew - 05 Apr 2007 22:21 GMT
>>> Why did you choose Vector over other List implementations? Better
>>> alternatives
[quoted text clipped - 17 lines]
> index), the latter being part of the List API, and the former being part
> of the pre-List API of Vector.

Also, all the methods in Vector and Hashtable are synchronized, an overhead
not needed in thread-local contexts.  Furthermore, the Collections class can
make synchronized versions of any collection.

Sun has massive tutorials about most Java stuff.
<http://java.sun.com/docs/books/tutorial/index.html>

Collections are covvered in
<http://java.sun.com/docs/books/tutorial/collections/index.html>
<http://java.sun.com/javase/6/docs/technotes/guides/collections/index.html>

You should spend lots and lots of time in the API docs, to which Oliver
already provided one link.
<http://java.sun.com/javase/6/docs/api/>
in particular
<http://java.sun.com/javase/6/docs/api/java/util/Collection.html>
and related links will help with collections.

Signature

Lew

Mike Schilling - 06 Apr 2007 07:46 GMT
> Also, all the methods in Vector and Hashtable are synchronized, an
> overhead not needed in thread-local contexts.  Furthermore, the
> Collections class can make synchronized versions of any collection.

And, still further, method-level synchronization of a collection is often
not terribly useful. Straightforward-looking code like

   for (int i = 0; i < list.size(); i++)
   {
       Object o = list.get(i);
       ...

can fail to do the desired thing, either silently or noisily.

Hmm, this is interesting.  From the javadoc for
Collection.synchronizedList()

 It is imperative that the user manually synchronize on the returned list
when iterating over it:
   List list = Collections.synchronizedList(new ArrayList());
       ...
   synchronized(list) {
       Iterator i = list.iterator(); // Must be in synchronized block
       while (i.hasNext())
           foo(i.next());
   }

This strongly implies, without actually saying so, that a synchronized list
is synchronized on itself.
Chris Uppal - 06 Apr 2007 09:00 GMT
> Also, all the methods in Vector and Hashtable are synchronized, an
> overhead not needed in thread-local contexts.  Furthermore, the
> Collections class can make synchronized versions of any collection.

Unfortunately, that's not quite true.  /Some/ of the methods in Vector and
Hashtable are synchronised, including all the methods from "classic" Vector and
Hashtable.  But the methods which they gained as part of the retrofitting to
the Collections framework (the ones inherited unaltered from AbstractList and
Dictionary) are not explicitly synchronised, and are not always safe.  Worse,
there is no way of telling which of the "new" methods are safe except by
inspecting the sources to java.util.*.  Similarly, there is no way of telling,
just from reading code which uses a Vector or Hashtable, whether it is using
methods from the safe "classic" set or from the potentially unsafe new
Collections set.

(I'd cite examples, except that I can't remember the details off-hand, and
don't want to go grubbing around in the source to rediscover them.)

   -- chris
Patricia Shanahan - 06 Apr 2007 12:55 GMT
>> Also, all the methods in Vector and Hashtable are synchronized, an
>> overhead not needed in thread-local contexts.  Furthermore, the
[quoted text clipped - 10 lines]
> methods from the safe "classic" set or from the potentially unsafe new
> Collections set.

<rant>

Every library function in Sun's C library documentation is tagged with
an "MT-level" attribute indicating its multithread behavior.

To see an example, go to docs.sun.com and search for e.g. malloc.

In these terms, most of the java.util methods are either unsafe or MT-safe.

Why isn't there a corresponding Javadoc tag, with an appropriate value
for every API method?

</rant>

Patricia
Lew - 06 Apr 2007 14:24 GMT
Lew wrote:
>>> Also, all the methods in Vector and Hashtable are synchronized, an
>>> overhead not needed in thread-local contexts.  Furthermore, the
>>> Collections class can make synchronized versions of any collection.

Chris Uppal wrote:
>> Unfortunately, that's not quite true.  /Some/ of the methods in Vector
>> and Hashtable are synchronised, including all the methods from "classic"
[quoted text clipped - 6 lines]
>> using methods from the safe "classic" set or from the potentially unsafe new
>> Collections set.

Wow.  Thank you for this information.

You have thrown petrol on the fire of my contempt for Vector and Hashtable.

Signature

Lew

Chris Uppal - 07 Apr 2007 13:48 GMT
> Wow.  Thank you for this information.

Sadly, it turned out not to be information after all.  My mistake.

   -- chris
Lew - 07 Apr 2007 15:37 GMT
> Sadly, it turned out not to be information after all.  My mistake.

The newsgroups are perfect for this sort of exchange - I've had many erroneous
notions dashed to the rocks.

Some turned out not to be so much erroneous as approximate.

The fact that all Vector's and Hashtable's (public) methods are synchronized
is part of the argument against it.  The other part you alluded to, that they
contain legacy methods that are not part of the collections framework, whose
use runs in conflict with the collections methods.

My issue isn't so much with the classes themselves as with the pedagogic
epidemic that spreads their use without proper education.  I would think that
since 1998 all Java training would begin with the collections framework
classes, and teach. e.g., the List interface first and ArrayList second, with
mention of Vector relegated to an appendix in the second-semester textbook.

Apparently not so.

One should never see Vector or Hashtable or Enumeration in introductory Java
exercises.

Signature

Lew

Chris Uppal - 07 Apr 2007 13:15 GMT
> Every library function in Sun's C library documentation is tagged with
> an "MT-level" attribute indicating its multithread behavior.
>
> To see an example, go to docs.sun.com and search for e.g. malloc.

Out of curiosity, what are the "levels" of thread-safety in that convention ?
Sun's server was taking several minutes to follow each link when I looked for
the malloc() documentation, so I didn't try to find a direct statement in the
their documents.

   -- chris
Patricia Shanahan - 07 Apr 2007 15:59 GMT
>> Every library function in Sun's C library documentation is tagged with
>> an "MT-level" attribute indicating its multithread behavior.
[quoted text clipped - 5 lines]
> the malloc() documentation, so I didn't try to find a direct statement in the
> their documents.

Unfortunately, I have not found a way of forming a URL for a deep point
in the documentation. Here are the levels, with my summary of the
meanings. Quoted material is copied from the web page.

Safe - functionally OK, but may be poor performance, such as a library
that treats all its code as a single critical region.

Unsafe - "An Unsafe library contains global and static data that is not
protected."

MT-Safe - "An MT-Safe library is fully prepared for multithreaded
access. It protects its global and static data with locks, and can
provide a reasonable amount of concurrency."

Async-Signal-Safe - Safe to call from signal handlers.

MT-Safe with Exceptions - See notes

Safe with Exceptions - See notes

Fork1-Safe - does proper lock clean-up for forking.

Cancel-Safety - safe to use with pthread cancel.

I don't claim these are the right classifications for Java. I don't
think, for example, that it would be a good idea to invoke Java code
inside a signal handler.

How about these:

Unsafe: All accesses should be synchronized externally. May modify
static data without synchronization.

Object-unsafe: Any static data access is synchronized, but caller is
responsible for ensuring instance methods only run in one thread at a
time. Can be done either by calling instance methods for a given object
in only one thread, or by synchronizing all instance method calls for a
given object on that object.

Safe: Only needs external synchronization to achieve consistency between
multiple calls.

Event-thread-only: Use in event handling thread only. (Most of Swing
would be designated Event-thread-only).

Patricia
a24900@googlemail.com - 07 Apr 2007 17:27 GMT
> How about these:

Some classes in the API require to acquire a central lock, via a
mechanism provided by the class. E.g.
http://java.sun.com/javase/6/docs/api/java/awt/Component.html#getTreeLock()

Also, there are classes where a combination of methods is save, while
other combinations are not. So:

> Object-unsafe: Any static data access is synchronized, but caller is

...

Partly-save: Only one or more particular sets of methods are thread
save when used in combination.

Save-if-procedure-followed: Caller is responsible for following an
outlined procedure. Instances are thread-save if procedure is
followed.

Partly-save-if-procedure-is-followed: Caller is responsible for
following an outlined procedure. A a particular set of methods is
thread-save if procedure is followed.

> Safe: Only needs external synchronization to achieve consistency between
> multiple calls.

> Event-thread-only: Use in event handling thread only. (Most of Swing
> would be designated Event-thread-only).

Maybe in more generic terms:

Designated-thread-only: Use in a designated thread only.

But qualifying a class/instances is not enough. Each method also needs
to be qualified individually. The class defines a convenient scope for
looking at a set of methods, but statements on class level can only
apply to how the methods interact as a whole. Particularly for partly-
save classes per-method  information is needed. E.g. UML has
sequential (not thread save), guarded (thread save, but one active
thread at a time only, others are blocked), and concurrent (thread
save, multiple threads at a time execute in parallel) methods.

That still doesn't cover all cases. E.g. cases where a method
invocation waits for a certain time until a lock becomes available and
prematurely returns if it doesn't, aren't covered.

But anyhow, it will be a cold day in hell when Sun starts to qualify
classes and methods.
Lars Enderin - 07 Apr 2007 17:41 GMT
a24900@googlemail.com skrev:
>> How about these:
>
[quoted text clipped - 3 lines]
>
> Also, there are classes where a combination of methods is save, while

Note that the word is "safe". "Save" is a verb.

> other combinations are not. So:
>
[quoted text clipped - 10 lines]
>
> Partly-save-if-procedure-is-followed: Caller is responsible for
Mike Schilling - 06 Apr 2007 16:41 GMT
>> Also, all the methods in Vector and Hashtable are synchronized, an
>> overhead not needed in thread-local contexts.  Furthermore, the
[quoted text clipped - 19 lines]
> (I'd cite examples, except that I can't remember the details off-hand, and
> don't want to go grubbing around in the source to rediscover them.)

Are you sure of this?  I just did the requisite grubbing in the 1.5.0
sources, and the only public methods not marked "synchronized" are those
which are implemented by calling a synchronized method.
Chris Uppal - 07 Apr 2007 13:46 GMT
> Are you sure of this?  I just did the requisite grubbing in the 1.5.0
> sources, and the only public methods not marked "synchronized" are those
> which are implemented by calling a synchronized method.

I have to recant: I thought I had such an example, but now I look again, all
the (relevant) methods of AbstractList /are/ overriden in Vector.

Sorry for the false alarm.

   -- chris
Andrew Thompson - 07 Apr 2007 15:44 GMT
..
>Sorry for the false alarm.

Cheers.  Deeply respect your opinion.  Not just for your
understanding of intricacies of matters relating to the finer
and more arcane aspects of Java and the JLS, but moreso
for your ability to recognise occasions when you may have
misunderstood what you saw.  Your candour is much
appreciated (hear, at least).

I enjoy reading your posts.

Signature

Andrew Thompson
http://www.athompson.info/andrew/

Patricia Shanahan - 07 Apr 2007 16:01 GMT
>> Are you sure of this?  I just did the requisite grubbing in the 1.5.0
>> sources, and the only public methods not marked "synchronized" are those
>> which are implemented by calling a synchronized method.
>
> I have to recant: I thought I had such an example, but now I look again, all
> the (relevant) methods of AbstractList /are/ overriden in Vector.

I don't think you should need to grub through the sources to find the
answer to a basic question about external functionality.

Patricia
Lew - 07 Apr 2007 17:06 GMT
Chris Uppal wrote:
>> I have to recant: I thought I had such an example, but now I look
>> again, all
>> the (relevant) methods of AbstractList /are/ overriden in Vector.

> I don't think you should need to grub through the sources to find the
> answer to a basic question about external functionality.

From
<http://java.sun.com/javase/6/docs/api/java/util/Vector.html>
> Unlike the new collection implementations, Vector is synchronized.

No grubbing in source required.

Signature

Lew

Mike  Schilling - 07 Apr 2007 18:40 GMT
>>> Are you sure of this?  I just did the requisite grubbing in the 1.5.0
>>> sources, and the only public methods not marked "synchronized" are those
[quoted text clipped - 6 lines]
> I don't think you should need to grub through the sources to find the
> answer to a basic question about external functionality.

You don't; that all the public methods of Vector are synchronized is fully
documented.

I could try to blame Sun for the fact that I felt it necessary to verify
this by hand, but that wouldn't be entirely fair :-)
Andrew Thompson - 30 Mar 2007 07:27 GMT
...
> If you are ...

..wanting help, it is best not to leave people..

>...wondering, ...

..what the heck is ..

>..in my real program, ..

..instead it is best to post an SSCCE.
<http://www.physci.org/codes/sscce.html>.
Rather than forcing potential helpers to make
changes to your example code so it actually
compiles and runs.  (And yes, like SadRed,
I changed that code until it would compile,
& by the time it compiled cleanly, it ran
flawlessly.)

Andrew T.
al.softdev@gmail.com - 30 Mar 2007 21:16 GMT
> Can someone show me why I am getting a null pointer exception from my
> code.  Here is a much simplified version:
[quoted text clipped - 27 lines]
> Thanks,
> Colin

Colin,

Didn't read through your code, but one likely scenario of getting this
error is if you have declared Vector and did not create an instance of
Vector before it has been used.

Try Vector<> v = new Vector(); before it has been used.

Al


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.