Threadlocal of a thread is accessible to main thread - java

How main thread is able to access threadlocal of another thread? Although threadlocal of another thread gives another value in main thread than what it gives inside its own run method.
class MyThread13 extends Thread{
static int id =0;
ThreadLocal threadLocal = new ThreadLocal(){
public Integer initialValue(){
return ++id;
}
};
public MyThread13(String name){
super(name);
}
public void run(){
System.out.println(Thread.currentThread().getName()+" is executing with id :"+threadLocal.get());
}
}
public class MultiThreading13ThreadLocalB {
public static void main(String[] args) {
MyThread13 myThread13a = new MyThread13("Thread:1");
MyThread13 myThread13b = new MyThread13("Thread:2");
myThread13a.start();
myThread13b.start();
myThread13c.start();
// myThread13d.start();
System.out.println("Accessing threadlocal from main :"+myThread13a.threadLocal.get());
}
}
when threadlocal of another thread is being accessed from main thread , it should give null. But here it is giving some other value

Your example shows a confusion of ThreadLocal with what are simply member variables of Thread instances. The concepts are similar; both allow you to associate state with a Thread instance, but a ThreadLocal allows you to do it outside of the thread instance itself. As you've noted, a ThreadLocal lives up to its name -- when you call get and set on it, those values are specific to that thread, which is why trying to access another thread's state (as the main thread tries to do in your example) is not going to work.
ThreadLocals are sometimes helpful, but in day to day programming there is rarely a need for them. One kind of use case would be something like a server process that accepts an incoming request and associates some state with that request; if you don't want to change all of your method signatures to pass that state through, you could put it in a ThreadLocal. Usually there is a single ThreadLocal instance per JVM.

Related

Init static variable in synchronized block for all the threads, read without synchronized

I often see the following pattern. One thread will initialize the client in init() method in synchronized block. All the other threads, also called init() method before they start to use the other class methods.
Client value is not changed after initialization. They dont set the client value as volatile.
My question is that if this is correct to do? Do all of the threads that create client, and call init() method , will after init method finished see the correct initilized value that was initialized byt the first thread that called init() method?
public class DB {
private static Object lock = new Object();
private static Client client;
public init() {
synchronized (lock) {
if (client != null) {
return;
}
client = new Client();
}
}
public insert(Object data) {
client.insert(data); // is this ok to access the client without volatile or synchronized?
}
}
The rationale behind that pattern is that they think that because they read the client under synchronized block in init() method, the client will be set to the correct initialized value, and because the client is never changed, they can use it without volatile or synchronized after. IS this correct assumption?
You can see this pattern for example here: https://github.com/brianfrankcooper/YCSB/blob/cd1589ce6f5abf96e17aa8ab80c78a4348fdf29a/mongodb/src/main/java/site/ycsb/db/MongoDbClient.java where they initialized the database in init method and used it without synchronization after.
It is only safe to do this if you are guaranteed to have called init() before calling insert(data).
There is a happens-before edge created by the synchronized block: the end of the synchronized block happens before the next invocation of the same block.
This means that if a thread has invoked init(), then either:
client was previously uninitialized, so it is initialized on this call.
client was previously initialized, and the write to client is has happened before the current thread enters the synchronized block.
No further synchronization is then necessary, at least with respect to client.
However, if a thread doesn't call init(), then there are no guarantees as to whether client is initialized; and no guarantee as to whether the client initialized by another thread (one that did call init()) will be visible to the current thread (the one that didn't call init()).
Relying on clients to call init() first is brittle. It would be much better either to use an eagerly-initialized field:
public class DB {
private static final Client client = new Client();
public insert(Object data) {
client.insert(data); // Guaranteed to be initialized once class loading is complete.
}
}
or, if you must do it lazily, use a lazy holder:
public class DB {
private static class Holder {
private static final Client client = new Client();
}
public insert(Object data) {
Holder.client.insert(data); // Holder.client is initialized on first access.
}
}
Or, of course, chuck in a call to init() inside the insert method:
public insert(Object data) {
init();
client.insert(data);
}
The disadvantage of the latter approach is that all threads must synchronize. In the other two approaches, there is no contention after the first invocation.
It looks like the rationale behind this type of pattern is to ensure that you can only have one instance of Client in the application. Multiple invocations (parallel/sequential) of init() method on different/same DB objects will not allow creating a new Client if it is already created and synchronized block is just to ensure that client object will be created only once if multiple threads called init() parallelly.
But it has nothing to do with safe call of insert() method on client object and that totally depends on the implementation of the insert() method that may be thread-safe or may not be.

How does multithreading method invocation work

I am using java.
I have an instance a of class A which has a public method foo() running and 2 other threads - threadB and threadC, all running at the same time.
here's class A
public class A {
int val = 0
public void foo(int incValue) {
a += incValue;
}
public static void main (String arg[]) {
MyThread a = new MyThread(this);
new Thread(a).start();
MyThread b = new MyThread(this);
new Thread(b).start();
}
}
here's the thread definition for threadB and threadC:
public class MyThread implements Runnable {
A main = null;
public MyThread(A main) {
this.main = main;
}
public callFoo(int incValue) {
main.foo(incValue);
}
#Override
public void run() {
//valToInc can be a value from a GUI form.
callFoo(valToInc);
}
}
If in threadB invokes callFoo(1) and threadC invokes callFoo(3) at the same time, then:
- Which thread will be able to call the method first?
- What is the result of the val in main class after both executions?
- Will the execution of the method for each thread happen concurrently or one after another?
There is absolutely no difference in how the JVM will invoke two methods "in parallel".
In other words: if you want to know what happens when a method is called, you can look here.
When a method is called "twice" in parallel, then that whole thing ... just happens twice!
Things become interesting when that method is making updates on that class, or in other objects! (like changing a field of your object, or appending a value to a list, ... )
You see, the real complexity of multi-threading is not about running some code in parallel. The real issue is what happens to "shared data".
If you find my answer to general; sorry - that is probably the best you can expect for such a generic question.
If [] threadB invokes callFoo(1) and threadC invokes callFoo(3) at the same time, then: - Which thread will be able to call the method first?
Threads run independently of each other. If there is no synchronization (there's none in your example), then any number of threads can be in calls to the same method at the same time.
Whenever a thread calls a method, it creates an activation record to hold all of the local variables and parameters of that method, and when several threads call the same method at the same time, each thread gets its own activation record. The threads can neither communicate with one another through the args and locals, nor can they interfere with one another's use of the args and locals.
They can, of course communicate and interfere with each other through any shared objects, including objects that may be referenced by the args or the locals.

Identifying two different threads

I am learning multithreading in java.My doubt is,is there any way two identify two different threads if they have same name below is my code
package com.rajeev.test2;
public class Test11 extends Thread {
public static void main(String[] args) {
System.out.println(Thread.currentThread());
new Test11().start();
new Test12();
}
#Override
public void run() {
Thread.currentThread().setName("ram");
System.out.println(Thread.currentThread());
}
}
class Test12 extends Thread{
static{
new Test12().start();
}
#Override
public void run() {
Thread.currentThread().setName("ram");
System.out.println(Thread.currentThread());
}
}
output
Thread[main,5,main]
Thread[ram,5,main]
Thread[ram,5,main]
I know they are two different threads having same name,so how to know they are different thread without changing name ?
Well you can track the Threads having same name by their ID which will be unique.
Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.
The JVM tracks threads by their ID, not by their name.
long threadId = Thread.currentThread().getId();
You should not use the name of the thread in order to identify a unique thread. The Thread class has a getId() method that returns a long number generated when the thread was created, and that is unique to the thread. Use this in order to know if they are different.
Using getId method
Use getId to identify the uniqueness of the Thread.
Thread id is to be set while creating a new thread. Irrespective of the constructor which will be used.
Thread()
Thread(Runnable, String)
Thread(Runnable)
Thread(String)
Thread(ThreadGroup, Runnable, String, long)
Thread(ThreadGroup, Runnable, String)
Thread(ThreadGroup, Runnable)
Thread(ThreadGroup, String)
all the constructors used init method. In this method has thread id generation.
Also In clone method also has thread id generation.
If Thread gets cloned , new thread id set for new thread reference.
Using equals & Hashcode method
Another way to identify thread uniqueness is using equals and hashcode.
Thread doesnt has same equals and hascode method.
So using hashcode to differentiate thread uniqueness.
You can simply compare the two objects of Test11 and Test12(i.e the threads) using equals operator.
Your example code is completely weird.
Never subclass Thread - there are very rare cases in which this is necessary.
Usually a Thread gets its name from the code that creates it. This makes it easy to give every new thread another distinct name. Do not set the name in the run method.
Please don't start threads in the static constructor of a class.
Probably your example should look simliar to that:
public class ThreadExample {
public static void main(String[] args) {
System.out.println(Thread.currentThread());
new Thread(new PrintThreadNameTask(), "thread-1").start();
new Thread(new PrintThreadNameTask(), "thread-2").start();
}
}
class PrintThreadNameTask implements Runnable {
#Override
public void run() {
System.out.println(Thread.currentThread());
}
}

What the use of Thread constructor with string param?

Looking at the Thread constructors, I see there is one that takes single string parameter. I have the below code, which is kind of useless. I would like to know, how to make a fruitful use of this constructor and make something actually run
public class ThreadTest {
public static void main(String[] args) {
Thread t = new Thread("abc");
t.start();
System.out.println("Complete");
}
}
Or Is it not supposed to be used the way I demonstrated above?
I perfectly know how to write multiple threads and execute :), I am just trying to understand the correct use of this constructor? Should it only be used by calling super(name) by extending Thread and not by the way I am using it above.
The thread class in itself doesn't do all that much. You have to extend it or construct it around a runnable to make it perform a task when run. From the doc:
start(): "Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread."
run(): "If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns."
Therefore constructing a new thread in your fashion and starting it does nothing. One use of the Thread(String) constructor is in subclasses:
public class Worker extends Thread{
public Worker(int numb){
super("worker-"+numb);
}
#Override
public void run(){
//Stuff this thread actually does when run
//....
for(int i = 0; i < 10; i++)
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
To answer your second question in the comments, this is how you would write code that's executed in parallel. Consider the above class plus this main method:
public static void main(String[] args){
Worker w1 = new Worker(1);
Worker w2 = new Worker(2);
w1.start();
w2.start();
}
The run methods of w1 and w2 will be executed in parallel. The order of the print statements will vary between executions of the main method.
This particular constructor is used to specify the 'name' of a thread, which can later be used to distinguish between instances of a specific thread type.
From the official Java API documentation;
Thread
public Thread(String name)
Allocates a new Thread object. This
constructor has the same effect as Thread (null, null, name).
Parameters: name - the name of the new thread
Once you have allocated a Thread a name, you can call the getName() method on the Thread instance to return the name it was given when it was created. This can be useful for debugging or for distinguishing between instances of of the same Thread subclass type.
Extra Reading:
Official Guide - Defining and Starting a Thread
If you simply call this constructor you get a Thread which does nothing. Why? Look at the source code of java.lang.Thread. It has a private Runnable target; class variable. When you call this constructor, the target variable remains set to null (because this constructor simply sets the Thread's name).
Also, the run() method of java.lang.Thread looks like this:
public void run() {
if (target != null) {
target.run();
}
}
So it means that this run() method will do nothing as target is null.
In order to create/start a Thread which really does something useful read here:
The Java tutorial - how to run a thread?

Concurrent access to static methods

I have a static method with the following signature:
public static List<ResultObjects> processRequest(RequestObject req){
// process the request object and return the results.
}
What happens when there are multiple calls made to the above method concurrently? Will the requests be handled concurrently or one after the other?
Answering exactly your question:
Method will be executed concurrently (multiple times in the same time if you have several threads).
Requests will be handled concurrently.
You need to add the synchronized modifier if you are working with objects that require concurrent access.
All your calls to the method will be executed concurrently... but:
You may have concurrency issue (and being in non thread-safe situation) as soon as the code of your static method modify static variables. And in this case, you can declare your method as synchronized
If your method only use local variables you won't have concurrency issues.
If you need to avoid concurrent execution, you need to explicitly synchronize. The fact that the method is static has nothing to do with it. If you declare the method itself to be synchronized, then the synchronization will be on the class object. Otherwise you will need to synchronize on some static object (since this doesn't exist for static methods).
I see a lot of answers but none really pointing out the reason.
So this can be thought like this,
Whenever a thread is created, it is created with its own stack (I guess the size of the stack at the time of creation is ~2MB). So any execution that happens actually happens within the context of this thread stack.
Any variable that is created lives in the heap but it's reference lives in the stack with the exceptions being static variables which do not live in the thread stack.
Any function call you make is actually pushed onto the thread stack, be it static or non-static. Since the complete method was pushed onto the stack, any variable creation that takes place lives within the stack (again exceptions being static variables) and only accessible to one thread.
So all the methods are thread safe until they change the state of some static variable.
You can check it yourself:
public class ConcurrentStatic {
public static void main(String[] args) {
for (String name: new String[] {"Foo", "Bar", "Baz"}) {
new Thread(getRunnable(name)).start();
}
}
public static Runnable getRunnable(final String name) {
return new Runnable() {
public void run() {
longTask(name);
}
};
}
public static void longTask(String label) {
System.out.println(label + ": start");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(label + ": end");
}
}
all method invocations from separate threads in java are concurrent by default.

Categories