Thread clarification in Java - java

Is it possible to synchronize the method when we extend Thread rather than implementing Runnable?
I know that when we use Runnable, it is possible. But when we do Thread t1 = new Thread();, can this be done?
How can it be synchronized?

Synchronization is orthogonal to the class on which the method is defined. You can use synchronized in any method. It just means there's a mutex guarding that block of code.
public class MyTotallyUnspecialClass {
synchronized public void someTotallyUnspecialMethod() {
// this method is synchronized, with a mutex on "this"
}
}

There is no effect on synchronization whether you extend Thread or implement Runnable. When you synchronize a method , you get a lock on the OBJECT and not the thread - so it really does not matter.There are many SO topics that discuss the distinction between these 2 approaches (extending thread vs implementing Runnable)

Related

Java multithreading server socket [duplicate]

Why sleep() and yield() methods are defined as static methods in java.lang.Thread class?
The code would only execute when someXThread was executing, in which case telling someYThread to yield would be pointless. So since the only thread worth calling yield on is the current thread, they make the method static so you won't waste time trying to call yield on some other thread.
This is because whenever you are calling these methods, those are applied on the same thread that is running.
You can't tell another thread to perform some operation like, sleep() or wait. All the operation are performed on the thread which is being executed currently.
If you call the yield or sleep method, it applies to whichever thread is currently executing, rather than any specific thread - you don't have to specify which thread is currently running to free up the processor.
similar thread in this forum
The same reason is why stop() and suspend() methods are deprecated. Intrusion in thread's state from outside is dangerous and can cause unpredictable result. And if sleep is not static, for example, how do you think interruption from it will happen?
They are static so that overriding concept can be avoided i.e.
When they are called with parent class reference to hold child class object like situation it implements Method Hiding concept and not overriding due to Static method nature, i.e parent class(here thread class) method will run which have the complete functionality of sleep and yield.
http://i.stack.imgur.com/goygW.jpg
Both sleep and yield methods are native. To understand better from above answers I made two classes ClassA and ClassB with same static method. I invoked method of other class to check its behavior. So we can call other class' static method.
So may be there is other reason behind making sleep method static.
public class ClassA {
public static void method(){
System.out.println("Inside ClassA method");
}
public static void main(String[] args) {
method();
ClassB classb = new ClassB();
classb.method();
}
}
public class ClassB {
public static void method(){
System.out.println("Inside ClassB method");
}
}
I know I am late to this party, (blame my parent :-))
I would like to answer this using proof by contradiction.
Let's say sleep method is not static so you can call sleep on any other thread object.
Let's say there are two threads, thread A and thread B. Now consider two possible scenarios in the context of sleep method, the same applies to yield as well.
System having single processor has only one thread active at a time, so if thread A calls sleep on thread B object i.e. B.sleep(), B is not in execution, as currently executing thread is thread A, so calling sleep on non-executing method is pointless.
A responsible programmer would never define sleep inside a synchronized block, or when a thread is holding a lock. But let's say thread A calls sleep method on thread B just when thread B is holding a lock(or inside a synchronized block), thread B would go to sleep holding lock which is totally undesirable.
These are just a few situations which forced jvm to not allowed thread to call sleep on another thread obect.

Two threads executing two `synchronized` methods?

I was reading about JAVA synchronization.
I have 2 methods in my class.
public synchronized void eat()
{
System.out.println("eat");
eatDinner();
}
public synchronized void eatDinner()
{
System.out.println("eat");
}
Both of my methods are synchronized.
Now Is it possible for 2 threads one is calling eat() and another eatDinner() to run simultaneously?
And If thread2 has not still executing eatDinner() . Can thread1 can call eatDinner() from eat()?
No, it is not possible for two threads to run the methods eat and eatDinner simultaneously. (Caveat: as long as these methods are invoked on the same instance of the class)
The synchronized keywords, when applied to a non-static method, synchronizes on the object itself.
Your code can be rewritten, without changing the meaning, as:
public void eat() {
synchronized (this) {
System.out.println("eat");
eatDinner();
}
}
public void eatDinner() {
synchronized (this) {
System.out.println("eat");
}
}
This probably makes it easier to see that they are both synchronizing on the same monitor.
Each java object has a monitor.
As long as 'thread1' is holding the monitor of your object, it can enter other synchronized blocks on the same monitor. 'thread1' has to exit all synchronized blocks (exist the blocks as many times as it has entered them) before another thread can take ownership of the monitor.
So thread1 can call eatDinner if it is already in the eat method - no problem. But if thread2 is currently in the eat method, then thread1 will block when it calls eatDinner until thread2 has finished both eatDinner and eat.
Addition:
In response to your comment
#Raj: If two threads are created by same class instances, then?
It is not important how the threads were created - it doesn't matter if that happened from within the same class or from completely different locations in your code. Two different threads are always independent.
It only matters on which object's monitor you synchronize: each object instance has one 'monitor'. You can't see this monitor - it doesn't have a name, but it's there and it is used by the synchronized keywords and by the wait, notify and notifyAll methods defined in java.lang.Object.
"Now Is it possible for 2 threads one is calling eat() and another eatDinner() to run simultaneously? "
on the same instance, no. they will block and only one will execute at once. different class instances, yes, they will not block eath other.
"Can thread1 can call eatDinner() from eat()"
yes. the lock is reentrant.
If 2 threads call methods on different class instances they can run methods simultaneously

Can a class with getters separate from input processing methods be considered "thread-safe"?

I was reading though a book on Java and there was this exercise question where they declared a class with one private variable, one public void method that did some expensive operation to calculate and then set the private variable, and a second public method to return the private variable. The question was "how can you make this thread-safe" and one possible answer was "synchronize each of the two methods" and one other possible answer was "this class can not be made thread-safe".
I figured the class could not be made thread-safe since even if you synchronize both methods, you could have a situation that Thread1 would invoke the setter and before Thread1 could invoke the getter, Thread2 might execute and invoke the setter, so that when Thread1 went and retrieved the result it would get the wrong info. Is this the right way to look at things? The book suggested the correct answer was that the class could be made thread safe by synchronizing the two methods and now I'm confused...
I figured the class could not be made thread-safe since even if you synchronize both methods, you could have a situation that Thread1 would invoke the setter and before Thread1 could invoke the getter, Thread2 might execute and invoke the setter, so that when Thread1 went and retrieved the result it would get the wrong info. Is this the right way to look at things?
You are correct with this. There is no way to guarantee that a thread will not have called either of the methods in between your calls of each of the methods, from within the class.
If you do want to do this, that will require a wrapper class.
So if the class with the getter and setter is like so:
class Foo
{
private static int bar;
public static synchronized void SetBar(int z) { ... }
public static synchronized int GetBar() { ... }
}
The wrapper class would look something like this:
class FooWrapper
{
public synchronized int SetGetBar(int z)
{
Foo.SetBar(z);
return Foo.GetBar();
}
}
The only way to guarantee this will work is if you can guarantee that all calls will go through your wrapper class rather than directly to class Foo.
When you make those two synchronized, the getter and setter themselves are thread-safe. More specifically:
When you call the setter, you are guaranteed that the value of the variable is what you set it to when the method finishes.
When you call the getter, you are guaranteed that the return value is the value of the variable when you made the call.
However, making the getter and setter themselves thread-safe does not mean that the application as a whole (i.e. whatever is using this class) is thread-safe. If your thread wants to call a setter then get the same value upon invoking the getter, that involves synchronization on a different level.
As far as thread-safety is concerned, a thread-safe class need not control how its methods are invoked (for example, it need not control which way the threads interleave their calls), but it needs to ensure that when they are, the methods do what they are supposed to.
synchronized in Java is an object-wide lock. Only one synchronized method of any given object can be executed on any given thread at a time. Let's have this class:
class Foo
{
private int bar;
public synchronized void SetBar() { ... }
public synchronized int GetBar() { ... }
}
Thread 1 calls SetBar(). Thread 1 acquires the object lock.
Thread 2 wants to call SetBar(), but Thread 1 holds the lock. Thread 2 is now queued to acquire the lock when Thread 1 will release it.
Thread 1 finishes executing SetBar() and releases the lock.
Thread 2 immediately acquires the lock and starts executing SetBar().
Thread 1 calls GetBar(). Thread 1 is now queued to acquire the lock when Thread 2 will release it.
Thread 2 finishes executing SetBar() and releases the lock.
Thread 1 acquires the lock, executes GetBar(), and is done with it.
You did the work twice, but you didn't cause any race condition. It may or may not be erroneous to do the work twice, depending on what it is.
A frequent pattern is to have one thread produce content and one other thread do something useful with it. This is called the producer-consumer pattern. In this case, there is no confusion over who or what tries to SetBar() and what tries to GetBar().

Question on threads

I am just playing around with threads in java. I have a class which implements runnable.
public class MyThread implements Runnable{
private boolean finished;
//Other variables
public void run(){
//Thread code
}
}
My understanding is that each thread of type MyThread will have its own copy of member variables and writes to those member variables need not be synchronized. Is this assumption correct? If correct, access to what needs to be synchronized? Can someone care to give a outline or pseudo code.? Thanks.
Not necessarily. You could create multiple threads using the same instance of MyThread. For example:
MyThread x = new MyThread();
new Thread(x).start();
new Thread(x).start();
new Thread(x).start();
Now there will be three threads all running code in the same object.
I suggest you rename MyThread as it's not a thread - it's a task for a thread to perform. That makes it clearer (IMO).
Each MyThread instance is a new instance, just like normal classes and objects.
Variables of native types are copied. This means that changing the variable in one thread does nothing to the other thread. These do not have to be synchronized.
For objects their references are copied. This means that two threads may have a reference to the same object. If the two threads manipulate that object at the same time, this can go bad. Therefore, these accesses have to be synchronized.
The Really Big Index trail on concurrency is well worth a read (yes, it has examples).

Java: A synchronized method in the superclass acquires the same lock as one in the subclass, right?

class A {
public synchronized void myOneMethod() {
// ...
}
}
class B extends A {
public synchronized void myOtherMethod() {
// ...
}
}
// ...
B myObject;
// ...
myObject.myOneMethod(); // acquires lock
myObject.myOtherMethod(); // same lock?
How I understand the synchronization model, I'd say that yes, it does, because the lock / monitor is associated with the instance myObject, and it doesn't matter where the method was defined. But am I right? If not, why? If yes, why are you sure, and I'm not? :-)
Yes, you are right, and you got the explanation right too. Nothing much to add.
Note that if the methods were static, then they would synchronize on different objects, namely their respective classes (A and B).
EDIT: Why am I sure? I don't know, why are you not sure? ;-) myObject is just one object - there isn't any distinction between the myObject attributes that come from class A and those that come from class B. (Well, technically you could probably use reflection to find out which are which, so there must be some distinction, but forget about reflection for now. For common operations on the object there's no distinction.)
Yes, synchronized is equivalent to synchronized(this).
To be more precise:
For a class (static) method, the lock associated with the Class object for the method's class is used. For an instance method, the lock associated with this (the object for which the method was invoked) is used.
If you want to be more explicit about your locking, you could do something like this:
class A {
protected final Object mutex = new Object();
public void myOneMethod() {
synchronized (mutex) {
// ...
}
}
}
class B extends A {
public void myOtherMethod() {
synchronized (mutex) {
// ...
}
}
}
In fact, this pattern is recommended by Brian Goetz in Java Concurrency in Practice, section 4.2.1 "The Java monitor pattern". That way you know exactly where your monitor is coming from.
Yes. Java uses "monitors" to implement synchronization, and synchronized methods use the object instance they're called on as monitor, which is obviously the same in this case.
Note that this is NOT true for static methods! There, the class instance of (I think) the declaring class is used, which would not be the same one.
Yes you are correct
When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object. In this case the object is B
Just a small addition for people who might be interested in the future..
Additionally remember that locks in Java are reentrant. If they were not this code of yours would result in a deadlock since as you've indicated both operations require the same lock.
From the conceptual viewpoint, the mutex integrity of some inheritance scenarios would be broken if synchonized methods of class A would only protect A's data in the context of subclass B. After all, not all of A's data is required to be private.
Imagine that you want to slightly extend the functionality of one method of A while keeping the rest of A's functionality including mutex protection. If A were only protecting itself, you would end up having to override all of A's synchronized methods to lift the original synchronization mechanism to the new subclass. Not very attractive and also not very efficient.

Categories

Resources