synchronization - How to maintain mutable state in a Java Singleton -


i have singelton in java (in osgi service) , want maintain state in (a counter).

should variable static? or synchronized? or both?

or should wrap actions in syncronized method? (would different making var syncronized?)

i want consumers of service actions increment counter.

public myserviceimpl implements myservice {     private int count = 0; // static? syncronized?      public string helloworld() { count++; return "hello world"; }     public int gethellocount() { return count; } } 

update: how map or list? preferred use atomic versions of these too? or synchronized better this?

the problem singletons require scope. if register service in osgi singleton in framework. however, since osgi avoids statics plague people start multiple frameworks (nested or siblings) in same vm , mean service gets registered multiple times in different frameworks. in general, want. if not sufficiently singleton, should scope? vm, process, machine, network, world? tricks people provide creating singletons forget tell scope class loader happen in.

in osgi, assume scope framework. register single service , use instance variables. since osgi runs in concurrent environment, must, other posts indicate, use synchronized methods or better atomiclong/atomicinteger.

if have multiple services need share singleton, create service represent singleton.

never use statics since can reduce reusability of code significantly, have evils of global variables. 1 of beauties of pure osgi allows program instances , never have work statics , class names (which suffer same global variable problem).


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -