• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronize this ??

 
Hussein Baghdadi
clojure forum advocate
Bartender
Posts: 3479
Clojure Mac Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64716
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd say this is more appropriate for the Servlets forum, so moving this topic there.
 
Peter Bell
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int operations are atomic. So in this case you don't need synchronization.
 
Vasim Patel
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic