I am asking this question is just for curiosity, I know it is stupid to do such thing.
public void doSomething()
{
synchronized(object_A){
count++;
average = count/total;
}
}
Now let say I have 2 thread run concurrently (calling function doSomething()), while the first thread already enter the block, let say at the line "count++", the second thread is blocked and waiting the lock.
Now I try to do object_A = new LockObject() (in another thread). Now what happen to thread 1 and thread 2?
Will thread 2 enter the block? Since it already executed statement "synchronized(object_A)", is it too late to change the lock?
Will thread 1 change the lock while in the sync block (assume thread 1 still in the block)?
It's like ignis said, but Thread 2 will see the new reference after Thread 1 is done, because it has to refresh all variables.
The only problem would be data integrity. Threads will be synchronizing on different locks and the data protected by the locks will have wrong values. Locks are created in the instance initializer's as private final fields or in the constructor of the class.
Related
This question already has answers here:
Threads access on Synchronized Block/Code Java
(2 answers)
Closed 5 years ago.
Say one singleton instance accessed by two threads. Two threads are accessing the same function called doTask().
public class MySingleton {
Object lock = new Object();
// I omit the constructor here.
public void doTask() {
//first non-synchronized code
synchronize(lock) {
//some heavy task
}
//final non-synchronized code
}
}
If thread B is doing the heavy task, when thread A access doTask(), I know Thread A will run the //first non-synchronized code, then thread A noticed the lock is acquired by Thread B, so it can't run synchronized //some heavy task. But would thread A skip the synchronized heavy task continue run //final non-synchronized code or will thread A wait for the lock without even executing the //final non-synchronized code?
(I know I can try it out, but currently I don't have a proper development environment...)
The synchronized block in java forces threads to wait until they can acquire the object's lock.
It will wait until B is done, and then snag the lock for lock, and run the code inside the block, and continue out the other end.
It is important to note that when B finishes executing the contents of some heavy task it will release the lock on lock and run the final non-synchronized code at the "same time" that A runs the synchronized block.
When one thread acquires the monitor of synchronous object, then the remaining threads will also try to acquire it and this process is termed as POLLING. Because all the remaining threads try to acquire the monitor of that object by repeatedly checking the monitor lock status. The moment when the lock is released it can be acquired by any thread. It's actually decided by the scheduler.
Thread A will always wait indefinitely until Thread B releases the lock.
In the extreme case, if the lock is never released, Thread A will be stuck forever.
Sometimes this is good enough but often you will need better control over things, this is when classes like ReentrantLock come handy.
This can do everything synchronized offers, but can also do things like checking whether the lock is owned by the current thread already, attempting to acquire the lock without waiting (failing instantly if the lock is already taken by another thread), or limit its waiting to a certain amount of time.
Please also note that while these solutions can be used to control mutual exclusion, this isn't their only function, they also play an important role in visibility.
Following are just three "happens-before" rules of JMM. I am not listing the other rules as my question is related to these three rules only.
Monitor lock rule. An unlock on a monitor lock happens before every
subsequent lock on that same monitor lock.
Thread start rule. A call to Thread.start on a thread happens before
every action in the started thread.
Interruption rule. A thread calling interrupt on another thread
happens before the interrupted thread detects the interrupt (either
by having InterruptedException thrown, or invoking isInterrupted or
interrupted).
Questions
1st rule question - Let's say two threads A and B have synchronized blocks of code. Does the first rule mean that any variable set in a synchronized block in thread A, will be visible to the code in synchronized block of thread B, even if the variable is NOT declared as volatile?
2nd rule question - Let's say a thread A starts a thread B. Does the second rule mean that any variable set in a parent thread before calling start() will be visible to thread B even if the variable is NOT declared as volatile?
3rd rule question - Let's say a thread A interrupts a thread B. Does the third rule mean that any variable set in thread A before interrupting thread B will be visible to thread B after the interrupt is detected, even if the variable is not declared as volatile?
Finally, one more question:
In BlockingQueue documentation, it is said,
Memory consistency effects: As with other concurrent collections, actions in a >thread prior to placing an object into a BlockingQueue happen-before actions >subsequent to the access or removal of that element from the BlockingQueue in >another thread.
Does this mean any variable set in a thread A before enqueuing an object in the blocking queue will be visible to thread B after dequeuing the object from the queue, even if the variable is NOT declared as volatile?
Basically through the above questions, I am trying to understand if the memory flush happens after these events such that the variables need not be declared as volatile in these cases.
1st rule question - Let's say two threads A and B have synchronized blocks of code.
Threads don't have code. Threads execute code.
Does the first rule mean that any variable set in a synchronized block in thread A, will be visible to the code in synchronized block of thread B, even if the variable is NOT declared as volatile?
Yes, Suppose we have:
private int i;
private final Object lock = new Object();
void foobar(...) {
...
synchronized(lock) {
i = ...;
}
}
int getI() {
synchronized(lock) {
return i;
}
}
If thread A calls foobar(), and then thread B subsequently calls getI(), then thread B will get the new value of i.
But note! My example above does not include any way for you to prove which call actually happened first. If your program depends on those calls to happen in a particular order, then it's going to need more than just a mutex: It's going to need some means to make thread B wait() for thread A to perform the update.
2nd rule question - Let's say a thread A starts a thread B. Does the second rule mean that any variable set in a parent thread before calling start() will be visible to thread B even if the variable is NOT declared as volatile?
Yes, that's what it means.
3rd rule question...
Yes again.
... BlockingQueue ...
Yes again.
...Through the above questions, I am trying to understand if the memory flush happens after these events such that...
Don't even think about "memory flush". That is not part of the Java language: If it happens, it's an implementation detail, and you don't need to worry about it unless you are implementing a JVM.
The only concept you need to worry about is the "happens before".
Whenever the JLS says that A happens before B, it means that if A happens in thread 1, and B happens in thread 2, and you can prove that A actually did happen before B in real-time, then any field that was updated by thread 1 before A happened will be guaranteed visible in thread 2 after B happens.
This question already has answers here:
How can the wait() and notify() methods be called on Objects that are not threads?
(10 answers)
Closed 5 years ago.
I am just having hard time to understand concept behind putting wait() in Object class. For this questions sake consider if wait() and notifyAll() are in Thread class.
class Reader extends Thread {
Calculator c;
public Reader(Calculator calc) {
c = calc;
}
public void run() {
synchronized(c) { //line 9
try {
System.out.println("Waiting for calculation...");
c.wait();
} catch (InterruptedException e) {}
System.out.println("Total is: " + c.total);
}
}
public static void main(String [] args) {
Calculator calculator = new Calculator();
new Reader(calculator).start();
new Reader(calculator).start();
new Reader(calculator).start();
calculator.start();
}
}
class Calculator extends Thread {
int total;
public void run() {
synchronized(this) { //Line 31
for(int i=0;i<100;i++) {
total += i;
}
notifyAll();
}
}
}
My Question is that what difference it could have made? In line 9 we are acquiring lock on object c and then performing wait which satisfy the condition for wait that we need to acquire lock on the object before we use wait and so is case for notifyAll we have acquired lock on object of Calculator at line 31.
I am just having hard time to understand concept behind putting wait() in object class For this questions sake consider as if wait() and notifyAll() are in thread class
In the Java language, you wait() on a particular instance of an Object – a monitor assigned to that object to be precise. If you want to send a signal to one thread that is waiting on that specific object instance then you call notify() on that object. If you want to send a signal to all threads that are waiting on that object instance, you use notifyAll() on that object.
If wait() and notify() were on the Thread instead then each thread would have to know the status of every other thread. How would thread1 know that thread2 was waiting for access to a particular resource? If thread1 needed to call thread2.notify() it would have to somehow find out that thread2 was waiting. There would need to be some mechanism for threads to register the resources or actions that they need so others could signal them when stuff was ready or available.
In Java, the object itself is the entity that is shared between threads which allows them to communicate with each other. The threads have no specific knowledge of each other and they can run asynchronously. They run and they lock, wait, and notify on the object that they want to get access to. They have no knowledge of other threads and don't need to know their status. They don't need to know that it is thread2 which is waiting for the resource – they just notify on the resource and whomever it is that is waiting (if anyone) will be notified.
In Java, we then use objects as synchronization, mutex, and communication points between threads. We synchronize on an object to get mutex access to an important code block and to synchronize memory. We wait on an object if we are waiting for some condition to change – some resource to become available. We notify on an object if we want to awaken sleeping threads.
// locks should be final objects so the object instance we are synchronizing on,
// never changes
private final Object lock = new Object();
...
// ensure that the thread has a mutex lock on some key code
synchronized (lock) {
...
// i need to wait for other threads to finish with some resource
// this releases the lock and waits on the associated monitor
lock.wait();
...
// i need to signal another thread that some state has changed and they can
// awake and continue to run
lock.notify();
}
There can be any number of lock objects in your program – each locking a particular resource or code segment. You might have 100 lock objects and only 4 threads. As the threads run the various parts of the program, they get exclusive access to one of the lock objects. Again, they don't have to know the running status of the other threads.
This allows you to scale up or down the number of threads running in your software as much as you want. You find that the 4 threads is blocking too much on outside resources, then you can increase the number. Pushing your battered server too hard then reduce the number of running threads. The lock objects ensure mutex and communication between the threads independent of how many threads are running.
For better understanding why wait() and notify() method belongs to Object class, I'll give you a real life example:
Suppose a gas station has a single toilet, the key for which is kept at the service desk. The toilet is a shared resource for passing motorists. To use this shared resource the prospective user must acquire a key to the lock on the toilet. The user goes to the service desk and acquires the key, opens the door, locks it from the inside and uses the facilities.
Meanwhile, if a second prospective user arrives at the gas station he finds the toilet locked and therefore unavailable to him. He goes to the service desk but the key is not there because it is in the hands of the current user. When the current user finishes, he unlocks the door and returns the key to the service desk. He does not bother about waiting customers. The service desk gives the key to the waiting customer. If more than one prospective user turns up while the toilet is locked, they must form a queue waiting for the key to the lock. Each thread has no idea who is in the toilet.
Obviously in applying this analogy to Java, a Java thread is a user and the toilet is a block of code which the thread wishes to execute. Java provides a way to lock the code for a thread which is currently executing it using the synchronized keyword, and making other threads that wish to use it wait until the first thread is finished. These other threads are placed in the waiting state. Java is NOT AS FAIR as the service station because there is no queue for waiting threads. Any one of the waiting threads may get the monitor next, regardless of the order they asked for it. The only guarantee is that all threads will get to use the monitored code sooner or later.
Finally the answer to your question: the lock could be the key object or the service desk. None of which is a Thread.
However, these are the objects that currently decide whether the toilet is locked or open. These are the objects that are in a position to notify that the bathroom is open (“notify”) or ask people to wait when it is locked wait.
The other answers to this question all miss the key point that in Java, there is one mutex associated with every object. (I'm assuming you know what a mutex or "lock" is.) This is not the case in most programming languages which have the concept of "locks". For example, in Ruby, you have to explicitly create as many Mutex objects as you need.
I think I know why the creators of Java made this choice (although, in my opinion, it was a mistake). The reason has to do with the inclusion of the synchronized keyword. I believe that the creators of Java (naively) thought that by including synchronized methods in the language, it would become easy for people to write correct multithreaded code -- just encapsulate all your shared state in objects, declare the methods that access that state as synchronized, and you're done! But it didn't work out that way...
Anyways, since any class can have synchronized methods, there needs to be one mutex for each object, which the synchronized methods can lock and unlock.
wait and notify both rely on mutexes. Maybe you already understand why this is the case... if not I can add more explanation, but for now, let's just say that both methods need to work on a mutex. Each Java object has a mutex, so it makes sense that wait and notify can be called on any Java object. Which means that they need to be declared as methods of Object.
Another option would have been to put static methods on Thread or something, which would take any Object as an argument. That would have been much less confusing to new Java programmers. But they didn't do it that way. It's much too late to change any of these decisions; too bad!
In simple terms, the reasons are as follows.
Object has monitors.
Multiple threads can access one Object. Only one thread can hold object monitor at a time for synchronized methods/blocks.
wait(), notify() and notifyAll() method being in Object class allows all the threads created on that object to communicate with other
Locking ( using synchronized or Lock API) and Communication (wait() and notify()) are two different concepts.
If Thread class contains wait(), notify() and notifyAll() methods, then it will create below problems:
Thread communication problem
Synchronization on object won’t be possible. If each thread will have monitor, we won’t have any way of achieving synchronization
Inconsistency in state of object
Refer to this article for more details.
Answer to your first question is As every object in java has only one lock(monitor) andwait(),notify(),notifyAll() are used for monitor sharing thats why they are part of Object class rather than Threadclass.
wait and notify operations work on implicit lock, and implicit lock is something that make inter thread communication possible. And all objects have got their own copy of implicit object. so keeping wait and notify where implicit lock lives is a good decision.
Alternatively wait and notify could have lived in Thread class as well. than instead of wait() we may have to call Thread.getCurrentThread().wait(), same with notify.
For wait and notify operations there are two required parameters, one is thread who will be waiting or notifying other is implicit lock of the object . both are these could be available in Object as well as thread class as well. wait() method in Thread class would have done the same as it is doing in Object class, transition current thread to waiting state wait on the lock it had last acquired.
So yes i think wait and notify could have been there in Thread class as well but its more like a design decision to keep it in object class.
wait - wait method tells the current thread to give up monitor and go to sleep.
notify - Wakes up a single thread that is waiting on this object's monitor.
So you see wait() and notify() methods work at the monitor level, thread which is currently holding the monitor is asked to give up that monitor through wait() method and through notify method (or notifyAll) threads which are waiting on the object's monitor are notified that threads can wake up.
Important point to note here is that monitor is assigned to an object not to a particular thread. That's one reason why these methods are in Object class.
To reiterate threads wait on an Object's monitor (lock) and notify() is also called on an object to wake up a thread waiting on the Object's monitor.
These methods works on the locks and locks are associated with Object and not Threads. Hence, it is in Object class.
The methods wait(), notify() and notifyAll() are not only just methods, these are synchronization utility and used in communication mechanism among threads in Java.
For more detailed explanation, please visit : http://parameshk.blogspot.in/2013/11/why-wait-notify-and-notifyall-methods.html
This is just my 2 cents on this question...not sure if this holds true in its entirety.
Each Object has a monitor and waitset --> set of threads (this is probably more at OS level). This means the monitor and the waitset can be seen as private members of an object. Having wait() and notify() methods in Thread class would mean giving public access to the waitset or using get-set methods to modify the waitset. You wouldnt want to do that because thats bad designing.
Now given that the Object knows the thread/s waiting for its monitor, it should be the job of the Object to go and awaken those threads waiting for it rather than an Object of thread class going and awakening each one of them (which would be possible only if the thread class object is given access to the waitset). However, it is not the job of a particular thread to go and awaken each of the waiting threads. (This is exactly what would happened if all these methods were inside the Thread class). Its job is just to release the lock and move ahead with its own task. A thread works independently and does not need to know whihc other threads are waiting for the objects monitor (it is an unnecessary detail for the thread class object). If it started awakening each thread on its own.. it is moving from away its core functionality and that is to carry out its own task. When you think about a scene where there might 1000's of threads.. you can assume how much of a performance impact it can create. Hence, given that Object Class knows who is waiting on it, it can carry out the job awakening the waiting threads and the thread which sent notify() can carry out with its further processing.
To give an analogy (perhaps not the right one but cant think of anything else). When we have a power outage, we call a customer representative of that company because she knows the right people to contact to fix it. You as a consumer are not allowed to know who are the engineers behind it and even if you know, you cannot possibly call each one of them and tell them of your troubles (that is not ur duty. Your duty is to inform them about the outage and the CR's job is to go and notify(awaken) the right engineers for it).
Let me know if this sounds right... (I do have the ability to confuse sometimes with my words).
the wait() method will release the lock on the specified object and waits when it can retrieve the lock.
the notify(), notifyAll() will check if there are threads waiting to get the lock of an object and if possible will give it to them.
The reason why the locks are a part of the objects is because the resources (RAM) are defined by Object and not Thread.
The easiest method to understand this is that Threads can share Objects (in the example is calculator shared by all threads), but objects can not share Attributes ( like primitives, even references itself to Objects are not shared, they just point to the same location). So in orde to make sure only one thread will modify a object, the synchronized locking system is used
Wait and notify method always called on object so whether it may be Thread object or simple object (which does not extends Thread class)
Given Example will clear your all the doubts.
I have called wait and notify on class ObjB and that is the Thread class so we can say that wait and notify are called on any object.
public class ThreadA {
public static void main(String[] args){
ObjB b = new ObjB();
Threadc c = new Threadc(b);
ThreadD d = new ThreadD(b);
d.setPriority(5);
c.setPriority(1);
d.start();
c.start();
}
}
class ObjB {
int total;
int count(){
for(int i=0; i<100 ; i++){
total += i;
}
return total;
}}
class Threadc extends Thread{
ObjB b;
Threadc(ObjB objB){
b= objB;
}
int total;
#Override
public void run(){
System.out.print("Thread C run method");
synchronized(b){
total = b.count();
System.out.print("Thread C notified called ");
b.notify();
}
}
}
class ThreadD extends Thread{
ObjB b;
ThreadD(ObjB objB){
b= objB;
}
int total;
#Override
public void run(){
System.out.print("Thread D run method");
synchronized(b){
System.out.println("Waiting for b to complete...");
try {
b.wait();
System.out.print("Thread C B value is" + b.total);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
I want to write a code with two different threads. The first one does somethin, the second one waits a specific time. The thread that ends first should interrupt the other one.
My problem is now, that the thread, I initialized first, cannot access/interrupt the second one, it always gives out the "symbol not found"-error. If I swap the positions of the threads in the code, it is the same, only the other way around.
Is there a possibility, to make both threads "global" and accessable by the other one? Please give coding examples, where to put the public void main, the void run(), etc., if possible, so I just need to add the code itself.
Thanks
Code examples:
public class FTPUpload extends Thread {
public static void main (String args[]) {
_//some code_
final Thread thread1 = new Thread(){;
public void run() {
_//code of thread1_
}
final Thread thread2 = new Thread(){;
public void run() {
_//code of thread2_
}
thread1.start();
thread2.start();
}
}
For your question is (currently?) a bit vague, my answer may not be that helpful. But...
Try declaring the Thread objects first and use them later. So each might be know to the other.
You can create a bool static Variable which both can access and once one of them is finished sets it to true, and you have to check this variable during the job in each thread, either on different places or if you have a loop in the loop for example.
Alternatively you can write a dummy file somewhere by the thread finished 1st and keep checking if file exists in both threads. The main idea is having a shared resource both can access.
Read this Question it very informative: Are static variables shared between threads?
My Idea May not work up to some answers but the one with the file should actually work.
A typical solution for communicating between 2 threads is to use condition variables. Thread1 could block on the condition variable, then when Thread2 has done what it needs to do and wants to tell Thread1 to go, it signals Thread1 via the condition variable, thus releasing its block. Both threads must be initialized with the same condition variable. Here is an example.
If you want both threads to wait until the other is initialized, this can be performed using a barrier sync (called a CyclicBarrier in Java). If Thread1 hits the barrier sync first it will block, until the other thread hits the barrier sync. Once both have hit the barrier sync, then they will continue processing. Here is an example.
Both condition variables and barrier syncs are thread safe, so you dont have to worry about if you need to synchronize them or not.
The general principal is to create a lock and condition outside both threads. The first thread acquires the lock and signals the condition when done. The second thread acquires the lock and awaits the condition (with timeout if needed). I am very concerned that you are relying on Thread.interrupt() which is a bad plan.
final Lock lock = new ReentrantLock();
final Condition done = lock.newCondition();
...
// in thread 1 when finished
lock.lock();
try {
done.signalAll();
} finally {
lock.unlock();
}
...
// in thread 2 for waiting
lock.lock();
try {
done.await(30,TimeUnit.SECONDS); // wait for the done or give up waiting after 30s
} finally {
lock.unlock();
}
Using the lock will ensure that both threads see a consistent view of shared objects, whereas Thread.interrupt() does not guarantee you have passed a boundary
A refinement is to use a CountDownLatch
final CountDownLatch latch = new CountDownLatch(1);
...
// in thread 1
latch.countDown();
...
// in thread 2
latch.await(30,TimeUnit.SECONDS)
This abstracts away the lock.
Others have suggested effectively a spin lock scanning for a file on the file system. Such an approach could lead to thread starvation or if not slower performance than a lock or latch based solution... Though for inter-process as opposed to inter-thread within the one jvm, file based is ok
I recommend the book "Java Concurrency In Practice" if you think you know threading go to a bookshop, open the book and try to predict what the program on page 33 will do... After reading that page you will end up buying the book
Thread 1:
if(!conditionFullfiled) this.wait();
Thread 2:
if(conditionFullfiled) thread1.notify();
I want to wake up thread 1 from thread 2, when some condition is fullfiled. But isn't there a problem, when thread1.notify() is called if(!conditionFullfiled) ***HERE*** this.wait(); ?
To do obj.wait() and obj.notify(), you need to own the monitor of the object you're going to wait/notify on. In your code, you probably don't want thread1.notify(). Example:
Object someSharedObject = ...
Thread1:
synchronized(someSharedObject) {
// while NOT if for spurious wake ups.
while(!conditionFullfiled) someSharedObject.wait();
}
Thread2:
synchronized(someSharedObject) {
if(conditionFullfiled) someSharedObject.notify(); // this wakes thread1
}
The synchronized lock is on someSharedObject (can be this), which means the two threads will never clash. .wait() releases the currently held monitor, so Thread2 will not be blocked when Thread1 is waiting.
Edit: I learnt something about spurious wake ups. The .wait() must be done in a while loop - if is not enough. Why do threads spontaneously awake from wait()? . Thanks Enno Shioji for teaching me.
Edit: Clarified .wait() releases monitor.
You have 2 problems here.
you should not call wait() and notify() on thread object itself. Better way to do this is to use special lock object, e.g.
private Object lock = new Object();
......
lock.wait();
The next problem is that you have to call both wait() and notify into synchornized block, i.e.
syncronized(lock) {
// some code
lock.wait();
}
then in other place in code say:
syncronized(lock) {
lock.notify(); // this line will cause the wait to terminate and the first thread to continue.
}
It is convenient to localize both wait() and notify() wrapping methods in one class, so they have access to lock object.
For more information read
http://download.oracle.com/javase/6/docs/api/
http://download.oracle.com/javase/6/docs/api/java/lang/Thread.html
No problem at all since wait releases object lock (in case this).
It's a best practice to guard wait/notify conditions in while blocks - to avoid spurious wake-ups.
What object you use as "this"? If you invoke wait() on thread1 object, and both statements you have shown are wrapped in a loop like this:
new Runnable() {
synchronized (thread1) {
thread1.wait()
}
}
Then your code will work as you want. (First thread will halt when condition is false, and work otherwise).
The trick is that interactions on the thread object are synchronized, so one thread can not interrupt while other is working with the object.
EDIT:
It will be even better if you will synchronize not on the thread, but on some other object (you can simply create pure object to provide locks).