Accessing the main thread, How it works? - java

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.

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.

thread safety with two synchronized methods, one static, one non static

If a class has only two synchronized methods (both either static or non static), the class is considered to be thread safe. What if one of the methods is static and one non static? Is it still thread safe, or bad things can happen if multiple threads call the methods?
There are some similar threads like static synchronized and non static synchronized methods in threads which describe the method calls are not blocking each other. But I am curious to know whether bad things in the world of thread safety (like inconsistent state, race condition, etc) can happen or not.
Edit 1:
Since static methods can't call non static methods, there should be no thread conflict from this side. On the other hand if a non static method calls the static one, it has to acquire the class lock. Which would be still thread safe. So by just having two methods (one static one none) I don't see any thread conflict. Is that right? In other words the only case I can see to have an issue is when the non static method accesses some static variables. But if all accesses are done through methods then I don't see any issues with thread safety. These were my thoughts. I am not sure whether I am missing something here since I am a little bit new to java concurrency.
In Java, the following:
public class MyClass
{
public synchronized void nonStaticMethod()
{
// code
}
public synchronized static void staticMethod()
{
// code
}
}
is equivalent to the following:
public class MyClass
{
public void nonStaticMethod()
{
synchronized(this)
{
// code
}
}
public void static staticMethod()
{
synchronized(MyClass.class)
{
// code
}
}
}
As you see, static methods use this as monitor object, and non-static methods use class object as monitor.
As this and MyClass.class are different objects, static and non-static methods may run concurrently.
To "fix" this, create a dedicated static monitor object and use it in both static and non-static methods:
public class MyClass
{
private static Object monitor = new Object();
public void nonStaticMethod()
{
synchronized(monitor)
{
// code
}
}
public static void staticMethod()
{
synchronized(monitor)
{
// code
}
}
}
What if one of the methods is static and one non static? Is it still thread safe, or bad things can happen if multiple threads call the methods?
Bad things can happen.
The static method will lock on the class monitor. The instance method will lock on the instance monitor. Since two different lock objects are in use, both methods could execute at the same time from different threads. If they share state (i.e. the instance method accesses static data) you will have problems.
What if one of the methods is static and one non static? Is it still thread safe, or bad things can happen if multiple threads call the methods?
Synchronization works with monitor (locks) that is taken on object.
In case of static method it's object of Class's class and in case of instance method it's this or calling object.
Since both the objects are different hence both synchronized static and non-static method will not block each other in case of multi-threading. Both the methods will execute simultaneously.
What if one of the methods is static and one non static
Yes.. Bad things can happen. Because if you synchronize on a static method, then you will be locking on the monitor of the Class object not on the class instancei.e, you will be locking on MyClass.class.
Whereas when you are synchronizing on an instance (non-static) method, you will actually be locking on the current instance i.e, this . So, you are locking on two different objects. So, the behaviour will be undefined and certainly not correct.
PS : In multi-threading, as a rule of thumb, please remember - If bad things can happen, they will happen.
What if ... Is it still thread safe?
Can't answer that question without a complete example. The question of thread safety is never a question about methods: It's a question about corruption of data structures and about liveness guarantees. Nobody can say whether a program is thread safe without knowing what all of the different threads do, what data they do it to, and how they coordinate (synchronize) with one another.

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.

Can Thread method be used in my class without extending Thread Class

I am new to threads and while learning it i cant understand the following,
public class myClass
{
public static void main(String args[]) throws InterruptedException
{
String[] myString = {"Object","Classes","Static","Final"};
for(int i=0;i<myString.length;i++)
{
System.out.println(myString[i]);
Thread.sleep(2000);
}
}
}
How come I'm able to use thread method without extending Thread class?
sleep is a static method. It doesn't require an instance to be called.
There are only 2 ways to make a class/method 'threadable' in Java. Extending Thread or implementing Runnable. What you are doing there is Thread.sleep() which is simply saying sleep the current thread.
It is just a static method supplied by Thread and as you have discovered doesn't really have much to do with multithreading specifically. A static method means an object of the containing class does not need to be instantiated to invoke the method which is why you can call sleep() without extending Thread.
Read about static methods in the Java tutorial. Learn the basics of the language before playing with threads. Threads are a difficult thing to master, and if you don't know what a static method is, it's too early to start using them, IMHO.
Here you are using astatic member method of Thread class, that's why you are able to use the sleep() function without requiring an instance.
sleep() is a static method of the 'Thread' class. as you might know static methods are invoked directly by the sysntax
MyClass.myStaticMethod().
you don't need to instantiate a Thread object to call sleep() method.

Class initialization and synchronized class method

In my application, there is a class like below:
public class Client {
public synchronized static print() {
System.out.println("hello");
}
static {
doSomething(); // which will take some time to complete
}
}
This class will be used in a multi thread environment, many threads may call the Client.print() method simultaneously. I wonder if there is any chance that thread-1 triggers the class initialization, and before the class initialization complete, thread-2 enters into print method and print out the "hello" string?
I see this behavior in a production system (64 bit JVM + Windows 2008R2), however, I cannot reproduce this behavior with a simple program in any environments.
In Java language spec, section 12.4.1 (http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html), it says:
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the reference to the field is not a compile-time constant (§15.28). References to compile-time constants must be resolved at compile time to a copy of the compile-time constant value, so uses of such a field never cause initialization.
According to this paragraph, the class initialization will take place before the invocation of the static method, however, it is not clear if the class initialization need to be completed before the invocation of the static method. JVM should mandate the completion of class initialization before entering its static method according to my intuition, and some of my experiment supports my guess. However, I did see the opposite behavior in another environment. Can someone shed me some light on this?
Any help is appreciated, thanks.
My understanding of the quoted text is that the class initialization process is completed (will be initialized) before a static method declared by T is invoked.
will be initialized implies that the initialization process has been started and has terminated.
So it shouldn't be possible (to my understanding) that, while the static initializer is executed because Thread A called print, another Thread already can call print.
Chapter 12.4.2 of the JLS describes the detailed initialization procedure, which takes care of initializing classes in a multithreaded environment.
Executing static blocks considered to be a part of class initialization:
Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class...
It is guaranteed by JVM specification that that will be done in thread safe way. To quote JLS section 12.4.2 Detailed Initialization Procedure:
Because the Java programming language is multithreaded, initialization of a class or interface requires careful synchronization, since some other thread may be trying to initialize the same class or interface at the same time. There is also the possibility that initialization of a class or interface may be requested recursively as part of the initialization of that class or interface; for example, a variable initializer in class A might invoke a method of an unrelated class B, which might in turn invoke a method of class A. The implementation of the Java virtual machine is responsible for taking care of synchronization and recursive initialization...
In more detail, it's implemented by acquiring lock on Class object:
The procedure for initializing a class or interface is then as follows:
Synchronize (§14.19) on the Class
object that represents the class or
interface to be initialize
Your method is static synchronized and it requires lock on Class object as well. Since the same lock is acquired by JVM during class initialization it's not possible for one thread to initialize class and for other execute static synchronized method on it.
All quotes are taken from
JLS
I hope that's helpful. Btw, how do you know that print occurs before class initialization finishes?
EDIT: Actually I'm wrong about assumption that only static synchronized couldn't be executed in parallel with class initialization. Any methods on class couldn't be executed until class initialization finishes.
If your "multi thread environment" uses multiple class loaders to load your Client class it would be possible for you to get mulitple Client instances, each one of which would run the static initialiser prior to running any Client.print() calls. You would see something like
doSomething
hello
doSomething
hello
hello
hello
I have some sample code which shows this but the current version is a little fiddly to run. If you want I can clean it up and post it.
If the code is running in some containers such as Servlet, you could initialize it in container’s lifecycle.

Categories

Resources