This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Servlets and the fly likes Synchronize this ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Synchronize this ??" Watch "Synchronize this ??" New topic
Author

Synchronize this ??

Hussein Baghdadi
clojure forum advocate
Bartender

Joined: Nov 08, 2003
Posts: 3476

Hey folks.
I have created the following listener to track the current number of the users.

my question is should I synchronized the access to the users variable ?
another thing :
any ideas how to know the current number of online users (like 100 guests
and 40 members) ?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60737
    
  65

I'd say this is more appropriate for the Servlets forum, so moving this topic there.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Peter Bell
Greenhorn

Joined: Mar 25, 2003
Posts: 19
int operations are atomic. So in this case you don't need synchronization.


RimuHosting - JSP and Java Hosting
Vasim Patel
Ranch Hand

Joined: Apr 29, 2004
Posts: 87
In Java, the reading and writing of 32-bit or smaller quantities are guaranteed to be atomic
This applies only to reading and writing.

Take this
public void inc()
{
i++;
}

The above instruction actually consists of three instructions:

1) Read current setting of 'value'.
2) Increment the setting.
3) Write the new setting back.

Thus, the above code is not thread-safe.
However, this code snippet might translate into a single instruction on some CPUs and thus work correctly.
So it is better to synchronize it.
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Even if the increment were atomic (it isn't), the code would still not be threadsafe unless you made the variable volatile. Without this, you might run into problems with memory barriers and out-of-order execution. See the JLS for more details.

A final point. Synchronization is not expensive. Please don't even consider avoiding it until (a) you have shown using a profiler that it incurs significant performance or concurrency penalties, (b) these penalties are caused by the synchronization mechanism itself and not by improper use of it and (c) you know exactly what you're doing. Otherwise, don't go there. Here be dragons.

- Peter
[ August 14, 2004: Message edited by: Peter den Haan ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Synchronize this ??
 
Similar Threads
Is this thread safe?
Trying to find cause of NullPointerException
selection sort in a linked list
Thread Safe Code
Java help.