Why Not Use Instance Objects Instead of ThreadLocal in Java? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I was reading this article about ThreadLocal objects in Java in an attempt to understand why and when they would be used. In the article, I came across an example meant to demonstrate how to use ThreadLocal. It was a class that was supposed to be a transaction manager, and it used a static transactionID variable that was used throughout the class. In order to make the class thread safe, it used a ThreadLocal for the transactionID:
public class TransactionManager {
private static final ThreadLocal<String> context = new
ThreadLocal<String();
public static void startTransaction() {
//logic to start a transaction
//...
context.set(generatedId);
}
public static String getTransactionId() {
return context.get();
}
public static void endTransaction() {
//logic to end a transaction
//…
context.remove();
}
}
My question is, why not just make the transactionID an instance variable instead of making it static in the first place? That way you wouldn't need to use a ThreadLocal variable.

The difference would change on some scenarios, but let's try some things:
I will assume the outline of the example is something like "We are executing several steps in some process and we want to generate a transactionID to identify one execution of the process. All those steps run in the same thread for any given execution"
In this case, the difference would be that if you make it an instance variable (yes, you can do it), you will have to create your transactionId and propagate the TransactionManager instance across all the layers and classes you might need it as a parameter, making your methods signature dirtier than need to be (Imagine you have one StepExecution interface and all steps implements that interface, but not all steps might need to access the transactionID, you will then have one useless parameter mixed in your method signature)
Not only that, ThreadLocal will guarantee you that the value you are accessing is the one you generated on the same thread, preventing "leaks" of information among threads making it perfectly thread safe.

...and it used a static transactionID variable that was used throughout the class. In order to make the class thread safe, it used a ThreadLocal for the transactionID
That basically is the use-case for ThreadLocal in a nutshell: You have some body of non-thread aware code that you want to make thread-safe, but it uses one or more static variables. If it makes sense for each thread to have its own independent copy of the static variable, then you just pop in a ThreadLocal, and problem solved!

Related

Implement inner-class-like reference behaviour? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
First of all, allow me to explain a "behaviour" that I observed, then I will ask in "Example" section.
Inner-class-reference behaviour
In Java we can have (non-static) inner-classes, which seem to behave like having a strong-reference to their container-class and/or owner-class, but without causing memory-leak.
I mean, I observed that even if both owner-class and inner-class keep strong-reference to each other, the classes are garbage-collected anyway (once no external class references them, although having reference-recursion).
In other words, or in other programming-languages, where "reference-counters" are often used (unlike Java?);
We could achieve such behaviour if owner-class and all inner-classes share the same reference-counter. Where just like above, even if we only keep a single reference to inner-class, owner-class is kept as well.
Example (background and question)
My previous logic, which used above said behaviour, was something like:
public class WebApi {
public UserApi user = new UserApi();
public PostApi post = new PostApi();
protected String post(String url, String json) {
// ...
}
public class UserApi {
public void login() {
WebApi.this.post(...);
}
public void logout() {
WebApi.this.post(...);
}
// ...
}
public class PostApi {
// ...
}
}
Then day by day the project did grow, till each of UserApi and PostApi classes deserved their own separate files (instead of being inner-classes of one huge file).
How can we implement above described "Inner-class-reference" behaviour for external classes?
In Java we can have (non-static) inner-classes, which seem to "behave" like having a strong-reference to their container-class and/or owner-class, but without causing memory-leak.
I mean, I observed that even if both owner-class and inner-class keep strong-reference to each other, the classes are garbage-collected anyway (once no external class references them, although having reference-recursion).
Yes, that's how references work in Java: if an object is reachable, then it's retained, and if not, then it's (eventually) garbage-collected.
But how can we implement above described "Inner-class-reference" behaviour for external classes?
You don't need to do anything special: just give UserApi a field of type WebApi, and initialize it in the constructor.
Java's reference-tracing and garbage collection will ensure that, as long as any reachable UserApi instance holds a reference to a given WebApi instance, the WebApi instance is also considered reachable, and hence retained.

Alternative to delcare global variables in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
After reading global-variables-in-java, I found it's not suggested to declare global
variables. However, what's a better approach if I want to declare constant variables viewed by all methods in all classes. How to make those variables' scope global? How and why, thank you!
if I want to declare constant variables viewed by all methods in all classes
If those are really constants, then public static final fields are perfectly fine.
What kind of data is this? Does it need to externally configurable (at run time or build time)? Does it need to computed at application startup? Does that computation require external resources (such as files or networks) that may be unavailable or slow?
Well, the variables are indicating the state, in different drawing state(draw, erase...).
Not sure I understand what that means exactly, but maybe you want to define an enum?
I don't want to pass lots of parameter each time
That is a bad argument to use global variables.
Maybe you want to combine multiple arguments in a holder object?
Or have stateful objects with methods (as opposed to stateless functions that take many parameters).
But I still have to new a class containing these constants.
No. You can do
public final class MyConstants{
public static final String MY_OAUTH_KEY = "ABCDEFGH";
// maybe this should come from pom.xml
public static final String APP_VERSION = "0.0.1";
}
and then use it from anywhere in your code
System.out.format("You are running version %s%n", MyConstants.APP_VERSION);

Creating a factory - provide data in constructor or as parameter? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm creating a factory method that should wrapp some object creation. Question: would you rather provide the needed data in a constructor, or as param for the methods itself?
class PersonFactory {
//constructor only neccessary of no param in method
public PersonFactory(PersonDTO dto) {
this.dto = dto;
}
public Person createPerson(PersonDTO dto) {
//create the complex person
return person;
}
//more methods to come
}
What would you prever, and why?
new PersonFactory(dto).createPerson();
new PersonFactory().createPerson(dto);
Both options are valid.
It depends on whether you want to reach around factories which have their dto property already set or if you know that property only when you use the factory.
When the classes which use the factory shouldn't depend on the PersonDTO (whatever that is), it would make sense to have that attached as a private property to the factory.
But when the PersonDTO is an object which is created by the user of the factory, you would provide it to the create-method.
I would pick the new PersonFactory().createPerson(dto); because its more convenient. You dont need to make new instances of the factory class if you wish to create more objects.
I would go for the
createPerson(dto)
for me this is easier to test.
Also in such a case you do not actually need an instance of PersonFactory - you could simply make the method static.
The design rule I use for factories is:
Do the heavy work in the constructor
Make factory instances reusable (and ideally thread safe)
Do instance related stuff in the method
That means, I'd go with the new PersonFactory().createPerson(dto) approach.
Even if both ways were valid in this example, it is easier to follow one standard approach for all the factories you create. That way your code is much easier to understand later.

Is this appropriate to create a class with one method? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm wondering whether it's a good practice to produce the code which being used like this:
new TemplateProcessor(inputStream).processTemplate("output-path.xhtml");
Here, TemplateProcessor contains only one public method. It seems the code above can be expressed with a static method, but I would like to avoid that. The reason is simple: object may contain encapsulated state, (maybe now, maybe in the future). Dear experts what would You prefer in this case?
It's reasonable to encapsulate the code in a static method, with static imports it becomes very easy to use:
processTemplate(inputStream, "output-path.xhtml");
The above static method would just be a façade, a convenience method to be used for that specific use case that your class is solving, supposedly one that's very common. It does not prevent the class from evolving, even adding state. For more specialized use cases, the consumers can still create instances of the class and use its methods as usual.
To make that separation even more pronounced, you could add the static method to a sibling class, like TemplateProcessorFacade, which is a non-instantiatable utility class:
public final class TemplateProcessorFacade {
private TemplateProcessorFacade() {}
public static void processTemplate(...) {
...
}
}
A class should be seen as an object or module that performs a key role or function in the program. A role that no other class or module fulfils. For example, you can have a class Animal that provides the functions sleep(), run() . But you might want a class for carnivores which also kill() , hunt() etc. So you implement the Carnivores class by extending from Animal, which does what all variables of type Animal do, but also additionally kill and hunt.
If your class has only one public method, but if it's important for the design to have it as a separate module, then having a class for it is good. You can extend it later, if needed.
Also you can, keep the sleep() and run() functions static and public, all Animal's do that, and so you can just do Animal.sleep() and such, without creating a separate instance. But a function like roar() shouldn't be.
Update:
The reason I said, sleep() and run() can be static is, there can be a class Man who also sleeps and runs.
The question to ask:
Does it make sense to call sleep() and run() or any function of a class without initializing an object of that class? If yes, then it makes sense to make it static.

Java Utility Class vs. Service [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
What's the difference in Java between a utility class (a class with static methods) and a Service class (a class with public methods that provides a "service"). For example, one can argue that a cryptographic object (providing methods to encrypt, decrypt, hash or get a salt value) is a Service provider, but many group this functionality into a Utility class with static methods, like CryptoUtil.encrypt(...). I'm trying to figure out which way follows better "design". Thoughts?
Different behaviors can be obtained by using different service objects. Static methods in a utility class can't be swapped out. This is extremely useful for testing, changing implementations, and other purposes.
For example, you mention a CryptoUtil with an encrypt method. It would extremely useful to have different objects that could support different encryption strategies, different message recipients, etc.
The difference is that service classes might have state. And by state I mean conversational state. Consider a notional ordering system.
interface OrderSystem {
void login(String username, String password);
List<Item> search(String criteria);
void order(Item item);
void order(Item item, int quantity);
void update(Item item, int quantity);
void remove(Item item);
void checkout();
Map<Item, Integer> getCart();
void logout();
}
Such a thing could be done with stateful session beans (as one example), although in that case authentication would probably be covered more traditional EJB mechanisms.
The point here is that there is conversational state in that the results of one call affects subsequent calls. You could view static methods as a bunch of simple stateless services that execute locally.
A service has a much broader meaning that includes, but is not limited to, being:
stateful;
remote; and
implementation dependent (ie through an interface).
Best practice I think is to simply use static methods as convenience methods (especially given Java's lack of extension methods). Services are much richer than that.
You cannot override static method, which can be a huge problem in case you'd like to implement your service in two different ways and switch between them. For this reason, I would limit the use of static utility classes to simple things which will "never" (for sufficiently long value of "never" :)) need to be done in more than one way.
I think there are no hard and fast rules.
I typically use static methods for functionality that requires few parameters, and can be accomplished in a single method call. Example:
calculate a hash value for a string
convert a date to standard representation
If a functionality requires many parameters, and if there are several related results being created, then it's more practical to have a classe that can accept the shared parameters in its constructor, with several methods that perform the actual action.
Typical example: A database connection, which you first connect, then use to do a query, then use to get the result...
I answered this question here somewhere before, but what I found was that it was very easy to change the behavior of a Service--to refactor it into multiple services--where it takes a pretty significant refactor if you use a static class.
If that is the only difference (and I believe it is), then it never makes any sense to use static classes.
Any time someone says "There will never ever ever be more than 1 of these", code for n of them.

Categories

Resources