It's not a secret anymore!
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
JavaRanch » Java Forums » Java » Servlets
Bookmark "Synchronize this ??" Watch "Synchronize this ??" New topic

Synchronize this ??

Hussein Baghdadi
clojure forum advocate

Joined: Nov 08, 2003
Posts: 3479

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

Joined: Jan 10, 2002
Posts: 63866

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

[Asking smart questions] [About Bear] [Books by Bear]
Peter Bell

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()

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
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:
subject: Synchronize this ??
It's not a secret anymore!