Java multithreading server socket [duplicate] - java

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.

Related

Accessing the main thread, How it works?

consider the following code snippet
public class ThreadDemo{
public static void main(String[] args){
Thread t = Thread.currentThread();
t.setName("MainThread");
}
}
I know that each class automatically extends java.lang.Object. and this class does not extend or implement any other class or interface.
my question is since the class ThreadDemo is NOT extending or implementing any interface or class including Thread and Runnable.
How it is possible for us to use the class Thread in the main method to access the main thread?
I mean how it works??? Is it something about the JVM stuff?
You're calling the static currentThread() method of Thread, which returns the current thread (hence the name). Then you set its name.
There's nothing magical about this code (except that currentThread() is a native method).
how the JVM knows that I mean the main thread NOT any other thread?
The name "currentThread" is a bit of a misnomer. It dates back to a time when most computers had only one CPU, and so only one thread---the current thread---could be running at any given time.
On my laptop, there can be eight "current" threads, and on a big mainframe, there can be more than a hundred. What Thread.currentThread() does these days is return the identity of whatever thread called the method.
currentThread( ) is a public static member of the Thread class. It's general form is:
static Thread currentThread( )
This method returns a reference to the thread in which it is called.
Static methods can be called without creating an instance of the class, using the class name as follows:
ClassName.staticMethod( )
Since currentThread( ) is a static member method it is therefore used directly without creating an instance of the Thread class.

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

java: running thread methods in the same class

I have three threads on the same class i.e
Thread A obj, Thread B obj, Thread C obj and that class contains 3 static synchronized methods so when we start the 3 threadssaya.meth1, b.meth2, c.meth3what will happen – does all three will execute or only one ?`
Update:
interviewr asked me this question so actually i do have any code to write it here
The methods are static and synchronized.. So, the lock will be on the class object.. Not on the instances of the class.. So the methods will run one after another.... Thread2 and Thread3 will have to wait until thread1 completes method1().. syncronization is NOT at method level.. it is always at object level... beit instance object or class object.
then they will execute it one by one in serial manner as the methods are static synchronized. So the lock will be held at Class Level not the method level. Hence one thread will acquire lock and others will have to wait.
You should try running this and see.
Once you invoke a synchronized method, the VM will automatically ask a grant of access for the object on which you are invoking the method. If that is given it will enter the synchronized method. Upon exit til will release this access right. While holding the rights, no-one else is allowed into any synchronized method on the same object, effectively serializing the requests.
does that make sense?
Synchronization is designed to make things thread-safe and avoid race conditions, and this fashion reduce access to at most one thread. There is no way for the program to find out whether two synchronized methods A and B are otherwise connected, so it has the policy of least tolerance.
If you have more synchronization that necessary, e.g. that A and B needs to be mutually exclusive and C and D needs to be mutually exclusive, but not between, say A and C then the advice is typically to modularise your code so A+B goes into one object while C+D goes into another, hence avoiding to step over each others toes
If execution for objects of the same class attempt to enter the same synchronized method (whether static or not)from different threads, they will be synchronized (i.e. execute one at a time).
The primary difference between static synchronized methods and non static synchronized methodsis that non-static synchronized methods hold a lock on the instance of the class whereas static synchronized methods lock on the class object.
Since in java there exists one class object per class, only one thread can execute inside a static synchronized method in the same class.
For non-static synchronized methods only one thread can execute inside a static synchronized method in the same object
And one more point is that synchronization is at object level not as method level.

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().

Java Threads and synchronization

I have a web app that uses some jars written by me.
My challenge is that i have a critical (but fast) section in my code.
1 - I have an object of a given class that has a couple of static fields. Let's call this class A
2 _ A exposes a not static method that access the static fields. for reading and writting. Lets call this method doJob.
3 - Every request instantiates an object of the class A and calls doJob.
A a = new A(); a.doJob();
4 - I assume that every request is creating a new Thread where doJob is executed.
5 - If I define doJob as public synchronized void doJob () {//Do the job} only one Thread at a time will be executing the method and the others will keep waiting.
The question is: Is it all right what i am saying?
You are right, but doJob will be synchronized at instance level, so doJob method could be executed in the same time by two or more different threads on two or more instances of class A. If you want doJob to be executed only by one thread at a time (e.g because it chages static fields) you should either declare it static or synchronize the whole method body using a static field as locking object.
Given that you're trying to guard static (i.e. one per class) fields with non-static (i.e. one per object) monitors, I would say that the "only one thread at a time will be executing the method and the others will keep waiting" claim does not hold.
No.
Marking an instance method as synchronized means the same that doing
public void myMethod() {
synchronized(this) {
...
}
}
So, you can only guarantee that two threads are not running the same method of the same object. The same method from another object can be run simultaneously.
Try to synchronize with a more "static" object. I would use the class object itself, or some static (and inmutable) member.
yes, you're outline is correct. and it does technically bottleneck the system while the other threads wait for access. and this is perfectly fine and normal as long as you avoid putting any heavy processing or i/o within the synchronized block.

Categories

Resources