Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is synchronization needed while reading if no contention could occur

Consider code sniper below:

package sync;

public class LockQuestion {
    private String mutable;

    public synchronized void setMutable(String mutable) {
        this.mutable = mutable;
    }

    public String getMutable() {
        return mutable;
    }   
}

At time Time1 thread Thread1 will update ‘mutable’ variable. Synchronization is needed in setter in order to flush memory from local cache to main memory. At time Time2 ( Time2 > Time1, no thread contention) thread Thread2 will read value of mutable.

Question is – do I need to put synchronized before getter? Looks like this won’t cause any issues - memory should be up to date and Thread2’s local cache memory should be invalidated&updated by Thread1, but I’m not sure.

like image 352
Petro Semeniuk Avatar asked Dec 01 '10 22:12

Petro Semeniuk


People also ask

When should synchronization be used?

Synchronization is usually needed when you are sharing data between multiple invocations and there is a possibility that the data would be modified resulting in inconsistency. If the data is read-only then you dont need to synchronize. In the code snippet above, there is no data that is being shared.

Where synchronization is needed and why?

The need for synchronization originates when processes need to execute concurrently. The main purpose of synchronization is the sharing of resources without interference using mutual exclusion. The other purpose is the coordination of the process interactions in an operating system.

When should you synchronize threads?

Thread synchronization is the concurrent execution of two or more threads that share critical resources. Threads should be synchronized to avoid critical resource use conflicts. Otherwise, conflicts may arise when parallel-running threads attempt to modify a common variable at the same time.

What is the use of synchronization?

Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.


2 Answers

Rather than wonder, why not just use the atomic references in java.util.concurrent?

(and for what it's worth, my reading of happens-before does not guarantee that Thread2 will see changes to mutable unless it also uses synchronized ... but I always get a headache from that part of the JLS, so use the atomic references)

like image 127
Anon Avatar answered Oct 06 '22 03:10

Anon


It will be fine if you make mutable volatile, details in the "cheap read-write lock"

like image 37
Matt Avatar answered Oct 06 '22 03:10

Matt