I have two threads Thread1 and Thread2
//Within Thread1
synchronized(obj1)
{
obj1 = null;
}
//Within Thread2
synchronized(obj1)
{
do something
}
If jvm first executes thread1 and sets obj1 to null, then will thread2 see that change immediately or will it take time and jvm could still run the thread2 synchronized block since obj1 is not yet null?
This will almost certainly break the synchronization abstraction -- I wouldn't be confident that thread2 will see the change immediately. You should never change the reference of the object you're synchronizing on, much less set it to null, which will cause a NullPointerException on any further attempts to synchronize on it.
First let me emphasise that modifying a variable that is used for synchronization is a terribly bad thing. obj1 should be final and never be touched if it is used as a monitor.
That being said, back to your question:
If JVM first executes Thread1, it synchronizes on obj1, sets it to null and the thread exits. The second thread wants to synchronize on obj1, NullPointerException will be thrown. Because the modification of obj1 was made in synchronized block, it is guaranteed that Thread2 will see updated value (so: NullPointerException is guaranteed).
If Thread1 is interrupted after obtaining the lock on obj1 but before clearing the reference, Thread2 will lock on obj1 and wait until Thread1 finished. Then it will successfully enter the monitor because the object previously referenced by obj1 still exists.
synchronized synchronizes on the object, and not the reference. By setting obj1 (a reference) to null, thread2 can't synchronize on the object formerly pointed to by obj1, you'll get a NullPointerException instead.
A quick fix is to make the object a simple array of 1 element and refer to the array for synchronization, e.g.,
Object[] obj1 = {null};
The element can be null without impacting the existence of the array. Granted, this still breaks the "rule" of not using the object itself in synchronization, but unless your code complicates matters elsewhere, this quick fix should work as expected.
The change is immediate. When Thread 1 "owns" the lock, it can change the value of obj1 at will. Thread 2 has to wait until Thread 1 releases the lock. It will definitely see obj1 == null
Related
I'm wondering if there is an easy way to make a synchronized lock that will respond to changing references. I have code that looks something like this:
private void fus(){
synchronized(someRef){
someRef.roh();
}
}
...
private void dah(){
someRef = someOtherRef;
}
What I would like to happen is:
Thread A enters fus, and acquires a lock on someref as it calls roh(). Assume roh never terminates.
Thread B enters fus, begins waiting for someRef` to be free, and stays there (for now).
Thread C enters dah, and modifies someRef.
Thread B is now allowed to enter the synchronized block, as someRef no longer refers to the object Thread A has a lock on.
What actually happens is:
Thread A enters fus, and acquires a lock on someref as it calls roh(). Assume roh never terminates.
Thread B enters fus, finds the lock, and waits for it to be released (forever).
Thread C enters dah, and modifies someRef.
Thread B continues to wait, as it's no longer looking at someref, it's looking at the lock held by A.
Is there a way to set this up such that Thread B will either re-check the lock for changing references, or will "bounce off" into other code? (something like sychronizedOrElse?)
There surely is a way, but not with synchronized. Reasoning: At the point in time, where the 2nd thread enters fus(), the first thread holds the intrinsic lock of the object referenced by someRef. Important: the 2nd thread will still see someRef referencing on this very object and will try to acquire this lock. Later on, when the 3rd thread changes the reference someRef, it would have to notify the 2nd thread somehow about this event. This is not possible with synchronized.
To my knowledge, there is no built-in language-feature like synchronized to handle this kind of synchronization.
A somewhat different approach would be to either manage a Lock within your class or give someRef an attribute of type Lock. Instead of working with lock() you can use tryLock() or tryLock(long timeout, TimeUnit unit). This is a scheme on how I would implement this (assuming that someRef has a Lock attribute):
volatile SomeRef someRef = ... // important: make this volatile to deny caching
...
private void fus(){
while (true) {
SomeRef someRef = this.someRef;
Lock lock = someRef.lock;
boolean unlockNecessary = false;
try {
if (lock.tryLock(10, TimeUnit.MILLISECONDS)) { // I have chonse this arbritrarily
unlockNecessary = true;
someRef.roh();
return; // Job is done -> return. Remember: finally will still be executed.
// Alternatively, break; could be used to exit the loop.
}
} catch (InterruptException e) {
e.printStackTrace();
} finally {
if (unlockNecessary) {
lock.unlock();
}
}
}
}
...
private void dah(){
someRef = someOtherRef;
}
Now, when someRef is changed, the 2nd thread will see the new value of someRef in its next cycle and therefore will try to synchronize on the new Lock and succeed, if no other thread has acquired the Lock.
What actually happens is ... Thread B continues to wait, as it's no longer looking at someref, it's looking at the lock held by A.
That's right. You can't write code to synchronize on a variable. You can only write code to synchronize on some object.
Thread B found the object on which to synchronize by looking at the variable someref, but it only ever looks at that variable one time to find the object. The object is what it locks, and until thread A releases the lock on that object, thread B is going to be stuck.
I would like to add some more info on top of excellent answers by #Turing85 and #james large.
I agree that Thread B continues to wait.
It's better to avoid synchronization for this type of program by using better lock free API.
Atomic variables have features that minimize synchronization and help avoid memory consistency errors.
From the code you have posted, AtomicReference seems to be right solution for your problem.
Have a look at documentation page on Atomic package.
A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:
boolean compareAndSet(expectedValue, updateValue);
One more nice post in SE related to this topic.
When to use AtomicReference in Java?
Sample code:
String initialReference = "value 1";
AtomicReference<String> someRef =
new AtomicReference<String>(initialReference);
String newReference = "value 2";
boolean exchanged = someRef.compareAndSet(initialReference, newReference);
System.out.println("exchanged: " + exchanged);
Refer to this jenkov tutorial for better understanding.
My understanding of volatile is that it ensures that the value is always read from memory, so as far as I can see, in the following example, the myObject variable would need to be volatile to avoid a NullPointerException being raised:
private final Object lock = new Object();
private MyObject myObject = null;
//...
synchronized (lock) {
if (myObject == null) {
myObject = new MyObject();
}
myObject.blah();
// some other stuff that I want synchronized
}
myObject is only ever touched in the synchronized block. lock is only every used to synchronize that block.
Is that correct?
So rephrased slightly, my question is...imagine two threads are hitting that code. First thread locks and sets myObject, calls .blah() and any other code within the synchronized block and exits the synchronized block. This allows thread two to enter the synchronized block. Without setting myObject to volatile, is there are chance it could still evaluate myObject == null to true?
The synchronized block will ensure the updates to memory is seen by other threads. There is no need to make myObject volatile.
From Intrinsic Locks and Synchronization:
When a thread releases an intrinsic lock, a happens-before
relationship is established between that action and any subsequent
acquistion of the same lock.
I think volatile is not needed here, because every thread which goes into synchronized block is checking myObject references, so myObject should be instantieted when first thread goes into block, other threads are secured by checking is myObject not null. For me looks good.
EDIT: I hope there is only this one block where you want to use myObect reference, and you do not change this reference before or after synchoronize block.
Does the following code make sense:
Thread A:
synchronized(mObj) {
return mObj.x;
}
Thread B:
synchronized(mObj) {
mObj = new Object();
}
In particular, is it guaranteed that both synchronized sections will always be mutually exclusive?
No synchronized is not properly implemented here.
Every Object has a lock while execution thead acuire the lock and release it once it is done then the next thread will acuire who is waiting for that.
mObj = new Object();
reassigning new Object will make conflict on that.
Let assume a scenario - where 1st thread T1 is executing the synchronized section by acquiring the lock and thread t2 is waiting to get the lock which has acquired by thread T1. Now thread T1 reassign the mObj object with a new Object and leave the synchronized section by releasing the object (Old object) lock and thread t2 is now able to acuire the lock and get enter into the synchronized block.
At this point if thread T3 is trying to execute the synchrnized the block, "is the thread T3 able to acquire the Lock?". Answer is Yes. synchronized(mObj) now mObj reference is refering a new Object and no One has acquired the lock, so T3 can do it. so This is conflicting situation .
The lock is not on the variable, only the object.
Here is a schedule that shows this is not "thread safe" because the resulting schedule is not guaranteed.
mObj = X
synchronized(mObj) // B1 -> mObj evaluates to X
mObj = Y // B2
DoSomeWork() // B3
synchronized(mObj) // A1 -> mObj MAY evaluate to either X or Y
// because the evaluation of the variable is NOT
// within scope of the synchronization. If it
// evaluates to Y then it is NOT synchronized on X.
return mObj.x // A2 -> May or may not be mutually exclusive wrt B3
// (That is, neither case is "guaranteed".)
I've added a "DoSomeWork" at the end of the "Thread B" synchronized context to draw my argument, but I think the same logic/argument - that of it "may be X or Y" - can be applied without such and thus argued that the two synchronization blocks are not guaranteed to be mutually exclusive.
For your question "is it guaranteed that both synchronized sections will always be mutually exclusive"
Yes it will be mutually exclusive but not the way someone want.
Scenario 1: Lets say Thread1 got the monitor object and get inside the synchronize block first then obviously Thread2 will wait and reassigning mObj wont have any effect. Happy scenario :)
Scenario 2: Thread 2 gets the monitor lock and goes inside the synchronized block first and Thread 1 is waiting for mObj. Now when you reassign mObj to new object mObj1 it will change the monitor object and which will lead Thread 1 waiting for monitor lock for forever because when Thread2 will come out of synchronized block it will release lock for monitor object mObj1 not mObj. That's why i said, it's still mutually exclusive but not the way someone want :).
Scenario 3: If you are using wait-notify solution and then you do the same thing it will be catastrophically and cause you illeagalMonitorstate exception for the same reason as you are trying to wait or notify on some monitor on which you don't have lock/synchronized block as you reassigned the obj.
I came across a code like this
synchronized(obj) {
obj = new Object();
}
Something does not feel right about this , I am unable to explain, Is this piece of code OK or there is something really wrong in it, please point it out.
Thanks
It's probably not what you want to do. You're synchronizing on an object that you're no longer holding a reference to. Consider another thread running this method: they may enter and try to hit the lock at the moment after the reference to obj has been updated to point to the new object. At that point, they're synchronizing on a different object than the first thread. This is probably not what you're expecting.
Unless you have a good reason not to, you probably want to synchronize on a final Object (for visibility's sake.) In this case, you would probably want to use a separate lock variable. For example:
class Foo
{
private final Object lock = new Object();
private Object obj;
public void method()
{
synchronized(lock)
{
obj = new Object();
}
}
}
If obj is a local variable and no other thread is evaluating it in order to acquire a lock on it as shown here then it doesn't matter. Otherwise this is badly broken and the following applies:
(Posting this because the other answers are not strongly-worded enough --"probably" is not sufficient here -- and do not have enough detail.)
Every time a thread encounters a synchronized block,
before it can acquire the lock, it has to figure out what object it needs to lock on, by evaluating the expression in parens following the synchronized keyword.
If the reference is updated after the thread evaluates this expression, the thread has no way of knowing that. It will proceed to acquire the lock on the old object that it identified as the lock before. Eventually it enters the synchronized block locking on the old object, while another thread (that tries to enter the block after the lock changed) now evaluates the lock as being the new object and enters the same block of the same object holding the new lock, and you have no mutual exclusion.
The relevant section in the JLS is 14.19. The thread executing the synchronized statement:
1) evaluates the expression, then
2) acquires the lock on the value that the expression evaluates to, then
3) executes the block.
It doesn't revisit the evaluation step again at the time it successfully acquires the lock.
This code is broken. Don't do this. Lock on things that don't change.
This is a case where someone might think what they are doing is OK, but it probably isn't what they intended. In this case, you are synchronizing on the current value in the obj variable. Once you create a new instance and place it in the obj variable, the lock conditions will change. If that is all that is occurring in this block, it will probably work - but if it is doing anything else afterwards, the object will not be properly synchronized.
Better to be safe and synchronize on the containing object, or on another mutex entirely.
It's a uncommon usage but seems to be of valid in same scenarios. One I found in the codebase of JmDNS:
public Collection<? extends DNSEntry> getDNSEntryList(String name) {
Collection<? extends DNSEntry> entryList = this._getDNSEntryList(name);
if (entryList != null) {
synchronized (entryList) {
entryList = new ArrayList<DNSEntry>(entryList);
}
} else {
entryList = Collections.emptyList();
}
return entryList;
}
What it does is to synchonize on the returned list so this list does not get modified by others and then makes a copy of this list. In this special situation the lock is only needed for the original object.
so let's say that I have a static variable, which is an array of size 5.
And let's say I have two threads, T1 and T2, they both are trying to change the element at index 0 of that array. And then use the element at index 0.
In this case, I should lock the array until T1 is finished using the element right?
Another question is let's say T1 and T2 are already running, T1 access element at index 0 first, then lock it. But then right after T2 tries to access element at index 0, but T1 hasn't unlocked index 0 yet. Then in this case, in order for T2 to access element at index 0, what should T2 do? should T2 use call back function after T1 unlocks index 0 of the array?
Synchronization in java is (technically) not about refusing other threads access to an object, it about ensuring unique usage of it (at one time) between threads using synchronization locks. So T2 can access the object while T1 has synchronization lock, but will be unable to obtain the synchronization lock until T1 releases it.
You synchronize (lock) when you're going to have multiple threads accessing something.
The second thread is going to block until the first thread releases the lock (exits the synchronized block)
More fine-grained control can be had by using java.util.concurrent.locks and using non-blocking checks if you don't want threads to block.
1) Basically, yes. You needn't necessarily lock the array, you could lock at a higher level of granularity (say, the enclosing class if it were a private variable). The important thing is that no part of the code tries to modify or read from the array without holding the same lock. If this condition is violated, undefined behaviour could result (including, but not limited to, seeing old values, seeing garbage values that never existed, throwing exceptions, and going into infinite loops).
2) This depends partly on the synchronization scheme you're using, and your desired semantics. With the standard synchronized keyword, T2 would block indefinitely until the monitor is released by T1, at which point T2 will acquire the monitor and continue with the logic inside the synchronized block.
If you want finer-grained control over the behaviour when a lock is contended, you could use explicit Lock objects. These offer tryLock methods (both with a timeout, and returning immediately) which return true or false according to whether the lock could be obtained. Thus you could then test the return value and take whatever action you like if the lock isn't immediately obtained (such as registering a callback function, incrementing a counter and giving feedback to a user before trying again, etc.).
However, this custom reaction is seldom necessary, and notably increases the complexity of your locking code, not to mention the large possibility of mistakes if you forget to always release the lock in a finally block if and only if it was acquired successfully, etc. As a general rule, just go with synchronized unless/until you can show that it's providing a significant bottleneck to your application's required throughput.
I should lock the array until T1 is finished using the element right?
Yes, to avoid race conditions that would be a good idea.
what should T2 do
Look the array, then read the value. At this time you know noone else can modify it. When using locks such as monitors an queue is automatically kept by the system. Hence if T2 tries to access an object locked by T1 it will block (hang) until T1 releases the lock.
Sample code:
private Obect[] array;
private static final Object lockObject = new Object();
public void modifyObject() {
synchronized(lockObject) {
// read or modify the objects
}
}
Technically you could also synchronize on the array itself.
You don't lock a variable; you lock a mutex, which protects
a specific range of code. And the rule is simple: if any thread
modifies an object, and more than one thread accesses it (for
any reason), all accesses must be fully synchronized. The usual
solution is to define a mutex to protect the variable, request
a lock on it, and free the lock once the access has finished.
When a thread requests a lock, it is suspended until that lock
has been freed.
In C++, it is usual to use RAII to ensure that the lock is
freed, regardless of how the block is exited. In Java,
a synchronized block will acquire the lock at the start
(waiting until it is available), and leave the lock when the
program leaves the block (for whatever reasons).
Have you considered using AtomicReferenceArray? http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/atomic/AtomicReferenceArray.html It provides a #getAndSet method, that provides a thread safe atomic way to update indexes.
T1 access element at index 0 first, then lock it.
Lock first on static final mutex variable then access your static variable.
static final Object lock = new Object();
synchronized(lock) {
// access static reference
}
or better access on class reference
synchronized(YourClassName.class) {
// access static reference
}