>>> Bo Xu <[EMAIL PROTECTED]> 03-Nov-00 5:59:53 PM >>>
>If I have a int static class field whose default value is 0 in my
>Servlet class, and , I suppose I want to use it as a counter of
>all the client accessings to this Servlet class, so between
>the first accessing to I close the Servlet engine, can I always
>get the accessing times by this int static class field? is it very
>safe?
I see your problem.
Your problem is that you haven't tried to understand how threading
works in Java.
My advice is go and read a book that talks about threading. Or go and
read the archives of this list which explain the situation.
As a gesture of goodwill here's an example servlet which does what
you want:
public class Counter extends HttpServlet
{
Integer lock=new Integer(0);
int counter=0;
public void doGet(....
{
synchronized(lock)
{
counter++;
}
.
.
.
}
}
Note the "synchronized" block.
There are more elegant ways to do this - I like to declare a class
that has an accesible int, allowing me to synch on it and to increment
the counter by accessing the value directly - but this does work.
It's completely thread safe.
>I think there are other ways to solve it : for example, often
saving
>this field into a persistent media. But if I don't do it, can I be
sure
>that I can trust this counter?
How would this solve the problem? What if 2 or more threads tried to
save the counter to persistent media at the same time? You'd get a
crash.
Nic
___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".
Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html