vancan1ty
vancan1ty

Reputation: 563

synchronized statements java -- what exactly do they do vis-a-vis non synchronized code?

Do synchronized statements in java protect against modification of the object synchronized on in other threads which are accessing the thread WITHOUT synchronized statements? I am new to multithreaded programming and am confused by the documentation I've found on this issue.

Let's say I have the following code.

public class Test {
public ArrayList<Integer> items = new ArrayList<Integer>();

public Test(ArrayList<Integer> items) {
    this.items = items; 
}

public void perform() {
    synchronized(items) {
        int size = items.size();
        for(int n = 0; n < 10000; n++) {
              for(int i = 0; i < size; i ++) {
                  items.set(i, items.get(i) + 1);
              }
        }
    }
}

While the inner loop in "perform" is running, is it possible for "items" to be modified in another thread despite the fact that the whole loop is contained in a "synchronized(items)" statement? Or does the "synchronized" statement only protect against modification by other blocks which use "synchronized(items)" themselves to request the lock on "items"?

Thanks in advance for any help.

Upvotes: 1

Views: 119

Answers (3)

finejustice
finejustice

Reputation: 413

synchronized statements says it executes some "non-thread-safe" codes(or "critical area"), and blocks other threads that try to run synchronized statements(that means, non-thread-safe codes) until it completes.

but other thread that executes no critical area, will not be blocked.

And synchronized statements uses "mutex". mutex says an object, which one the critical area modifies. (which one in the synchronized declaration)

In case of yours, it is

items

.

other threads that uses different mutex, (not uses the "items") will not be blocked also.

below might help you: http://en.wikipedia.org/wiki/Mutual_exclusion http://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html

Upvotes: 0

Thorn G
Thorn G

Reputation: 12766

Synchronizing on an object does not mean no other thread can modify it. It means that other threads which also synchronize on that object must wait for your lock to be released.

Or does the "synchronized" statement only protect against modification by other blocks which use "synchronized(items)" themselves to request the lock on "items"?"

Thus, this statement is correct.

Upvotes: 3

Rob
Rob

Reputation: 6497

Threads executing code that modifies your items outside of a synchronized block are free to modify the items, even if another thread is executing the synchronized code. You have to be careful to synchronize everywhere (no help from the compiler or runtime system). This is one aspect that makes writing multi-threaded code difficult.

Upvotes: 3

Related Questions