Safe way to capture state of Application?
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 开发者_StackOverflow社区avoid using synchronize when access to state1 and state2 fields(which maybe slow down performance of application).
There are two aspects to the cost of synchronization.
The overhead of
synchronized
itself; andThe 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.
精彩评论