views:

32

answers:

1

If I have an Application like this:

Class Application {  
    List state1 = new ArrayList();  
    Map state2  = new HashMap();  
}  

And I have a RPC service run in an other thread that uses to report the state of Application(such as: how many item in state1, which are containing in state2 keys). What's the best way to do that? I'm finding the way to avoid using synchronize when access to state1 and state2 fields(which maybe slow down performance of application).

+1  A: 

There are two aspects to the cost of synchronization.

  1. The overhead of synchronized itself; and

  2. The cost of the operations performed within that block.

To give you an example:

public synchronized int[] getState() {
 return new int[] { state1.size(), state2.size() };
}

this is used for the lock. The operations in this case are extremely cheap (ie getting the size() of a Colleciton or Map). So the only overhead to worry about is the cost of synchronized itself.

In modern JVMs the cost of so low that it isn't even worth worrying about except in the most extreme of situations. By "most extreme" I mean where the number of such calls is incredibly large or the required latency is incredibly low (sub-microsecond).

So just use synchronized. It's far more readable and performance simply isn't an issue for what you want, unless there's something more to this.

cletus
but cletus, if I need to capture all keys of state2 like this: public synchronized List getAllKeys(){ List val = new ArrayList(); val.addAll(state2.keySet()); return val;}public synchronized void addItemToState2(Object k,Object v){ state2.put(k, v);} addItemToState2 is called so many times per seconds, getAllKeys is called rarely, but I still need to synchronize all the times, is it ok?Sorry, i'm learning to format message here :(.
secmask
@secmask my general advice is don't solve a problem until you *have* a problem. I could imagine you would add 1000 keys a second and wouldn't even notice the `synchronized` overhead on any semi-modern machine.
cletus