multithreading - Java SCJP/OCPJP -


given:

public class namedcounter{    private final string name;    private int count;    public namedcounter(string name) { this.name = name; }    public string getname() { return name; }    public void increment() { count++; }    public int getcount() { return count; }    public void reset() { count = 0; }   } 

which 3 changes should made adapt class used safely multiple threads? (choose three.)

a. declare reset() using synchronized keyword

b. declare getname() using synchronized keyword

c. declare getcount() using synchronized keyword

d. declare constructor using synchronized keyword

e. declare increment() using synchronized keyword

answers a, c, e. don't understand why. according synchronized keyword used manipulation operations. why answer c?

this question comes scjp dumps.

the jvm uses synchronized keyword tell when variable's contents need made visible across threads. in posted example not increment method unsafe (the postincrement operator takes multiple steps act, thread can interfere while increment in progress) methods touch count variable -- increment, reset, , getcount -- need synchronized keyword indicate count variable changed in thread. otherwise jvm perform optimizations caching value or eliminating bytecode altogether, because free reason code without taking account possibility of multithreaded access.

there alternatives synchronized here; instance atomicinteger work too, using count make sure value change atomically , accessed in way visible threads. question worded answers a, c, , e necessary.

answer d wrong because declaring constructor synchronized isn't valid syntax, , if valid wouldn't accomplish you. synchronization protects against sharing across threads, constructor call doesn't share there's nothing protect.

answer b wrong because name immutable object passed in constructor argument , assigned final instance member; since published safely , cannot change, synchronization unnecessary.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -