> I still use Vectors/Hashtables when I need thread safety, though. Does
> anyone know if it's faster/better to wrap one of the new
> collection classes in a Collections.synchronized* class instead?
I'd expect Vector/Hashtable to be a little faster: they subclass
ArrayList/HashMap, where synchronized Collections are proxies.
But, really, neither one works.
Any places you'd use a collection, it's usually insufficient to synchronize
the specific access: what you need to do is synchronize a block of accesses.
For instance, here's a simple cache of "Foo" objects (each identified by
name), implemented with a Hashtable:
Hashtable fooCache = new Hashtable();
public Foo getFoo(String name)
{
Foo foo = (Foo)fooCache.get(name);
if (foo == null)
{
foo = new Foo(name);
fooCache.put(name, foo);
}
return foo;
}
If you only want one Foo allocated per name--always--this caching mechanism
will break down. You'd need to synchronize around _all_ accesses to the
fooCache, whether it's a Hashtable or a HashMap. In other words,
synchronizing the table's access methods don't buy you anything--you need to
synchronize _across_ calls. And once you synchronize it correctly,
synchronizing specific methods just slows you down.
So, you should implement the above code as,
HashMap fooCache = new HashMap();
public Foo getFoo(String name)
{
synchronized (fooCache)
{
Foo foo = (Foo)fooCache.get(name);
if (foo == null)
{
foo = new Foo(name);
fooCache.put(name, foo);
}
return foo;
}
}
This may be a peculiar case for you, but you're probably doing something
which needs similar synchronization--whatever kind of collection you're
using.
-- Bill K.
> -----Original Message-----
> From: Jeff Kilbride [mailto:[EMAIL PROTECTED]]
> Sent: Monday, April 23, 2001 2:06 PM
> To: [EMAIL PROTECTED]
> Subject: Re: ArrayList vs. Vector
>
>
> I recently re-wrote some older java code (jdk 1.1 based) and
> one of my goals
> was to use the new collection classes. I moved all of my
> Hashtables/Vectors
> that didn't need to be thread safe to HashMaps/ArrayLists. No
> problems under
> Tomcat.
>
> I still use Vectors/Hashtables when I need thread safety, though. Does
> anyone know if it's faster/better to wrap one of the new
> collection classes
> in a Collections.synchronized* class instead? It just seems
> easier to me to
> use Vectors/Hashtables, since they're already internally synchronized.
>
> Thanks,
> --jeff
>
> ----- Original Message -----
> From: "Hunter Hillegas" <[EMAIL PROTECTED]>
> To: "Tomcat User List" <[EMAIL PROTECTED]>
> Sent: Monday, April 23, 2001 12:36 PM
> Subject: ArrayList vs. Vector
>
>
> > I use Vectors in some parts of my Web app and I'm thinking
> about using
> > ArrayLists instead...
> >
> > Any caveats to using them in a Web app environment?
> >
> > Hunter
> >
>