java - How do you ensure multiple threads can safely access a class field? -


when class field accessed via getter method multiple threads, how maintain thread safety? synchronized keyword sufficient?

is safe:

public class someclass {     private int val;      public synchronized int getval() {         return val;     }      private void setval(int val) {         this.val = val;     } } 

or setter introduce further complications?

if use 'synchronized' on setter here too, code threadsafe. may not sufficiently granular; if have 20 getters , setters , they're synchronized, may creating synchronization bottleneck.

in specific instance, single int variable, eliminating 'synchronized' , marking int field 'volatile' ensure visibility (each thread see latest value of 'val' when calling getter) may not synchronized enough needs. example, expecting

 int old = something.getval();  if (old == 1) {     something.setval(2);  } 

to set val 2 if , if it's 1 incorrect. need external lock, or atomic compare-and-set method.

i suggest read java concurrency in practice brian goetz et al, has best coverage of java's concurrency constructs.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -