In general, value passing between different classes is done with argument of method, For example, passing id value like this:
public class Controller {
private Service service = new Service();
void controllerMethod() {
Integer id = 5;
service.serviceMethod(id);
}
public static void main(String[] args) {
Controller c = new Controller();
c.controllerMethod();
}
}
public class Service {
private Dao dao = new Dao();
void serviceMethod(Integer id) {
dao.daoMethod(id);
}
}
public class Dao {
void daoMethod(Integer id) {
System.out.println(id);
}
}
These method calls are actually in a single thread, there are all in "main" thread. So I wonder if I can store this value in class 'Controller' in ThreadLocal and then get it from ThreadLocal in class 'Dao', but I failed.
public class Controller {
private Service service = new Service();
void controllerMethod() {
Integer id = 5;
System.out.println(Thread.currentThread().getName());
// ----add code
ThreadLocal<Integer> local = new ThreadLocal<>();
local.set(id);
// ----
service.serviceMethod();
}
public static void main(String[] args) {
Controller c = new Controller();
c.controllerMethod();
}
}
public class Service {
private Dao dao = new Dao();
void serviceMethod() {
System.out.println(Thread.currentThread().getName());
dao.daoMethod();
}
}
public class Dao {
void daoMethod() {
System.out.println(Thread.currentThread().getName());
// ----add code
ThreadLocal<Integer> local = new ThreadLocal<>();
System.out.println(local.get());
// ----
}
}
result:
I don't know why...Can this method be used to achieve passing value without argument actually? I hope someone can help me.
ps: Is there any other way to implement a no-arguments transfer of values between multiple classes?
A ThreadLocal
is usually used as a static variable:
public class Main {
private static final ThreadLocal<Integer> CURRENT_ID = new ThreadLocal<>(1);
private void method1() {
CURRENT_ID.set(100);
method2();
}
private void method2() {
System.out.println("ID: " + CURRENT_ID.get());
}
}
But for regular application code, you will almost never need to use ThreadLocal
directly. Even if it makes writing the code easier, always keep testing in mind! So in your case, I would consider to keep passing the necessary variables as parameters.
If you considered passing dependencies like DAOs or services via ThreadLocal, you should instead consider dependency injection.
When having method with too many parameters, instead of passing some parameters via ThreadLocal, have a look at parameter objects.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments