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

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.

Related

How to pass List<Object> objects to a constructor parameter (Object object1, Object object2)? [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 1 year ago.
Improve this question
My goal is to pass List<Object> objects to a constructor parameter Object object1, Object object2.
For example,
public class A {
public A(Object object1, Object object2) {
}
}
public class App {
public static void main(String[] args) {
List<Object> objects = new ArrayList<>();
objects.add(new Object());
objects.add(new Object())
A a = new A(...objects);
}
}
My expected result: It should work.
My actual result: The IDE throws error unexpected token.
Java, the language, has zero syntactical support for what you are trying to do here. And most likely never will, it is fundamentally tricky to do in java.
In general if you have a java method that takes a heap of arguments, all of which are of the same type, that's a badly designed method and you shouldn't be having it. Java could hypothetically grow a language feature that helps you out, but why cater to idiotic API designs, right?
Alternatively, you could have a List<Object> with a heterogenous (bunch of differently typed) objects, but you shouldn't have that either, it's un-java-like. Same cause for why java doesn't have this and probably never will: Why cater to bad code style?
Note that in java you can have 15 methods all with the same name differentiated solely by their types, so figuring out which one you actually intended to call is not necessarily simple.
You CAN do what you want with generics but it's a ton of code and very ugly:
public class Example {
public void callMe(String a, Integer b) {}
public void dynamicallyCallMe(List<Object> list) {
Method m = Example.class.getMethod("callMe", String.class, Integer.class);
m.invoke(this, list.toArray());
}
}
You do not want to this.
If you're facing a scenario where you do want this, then you'd want to change the environment some. For example, if these arguments are being provided by a user via a config script or whatnot, the method you are calling should be aware of this, and should therefore follow the interface public interface ConfigurableApp { void configure(List<String> aguments); } or whatnot. Make it explicit. Write a wrapper if you must, which would then be the place in your code where you perform any translations as needed.
If you're facing a more code-heavy config concept (where the config file needs to contain code, or code-esque constructions), then go all the way and make it a script file, run it with a script runner. Let them write that config file in javascript or what not and execute it from your java process.
And so on.
EDIT: With some more insights provided via the comments on this question:
What you're likely looking for is an SPI system that discovers factories.
SPI
SPI, or Service Provider Interface, is the name generally used in the java community for the idea of 'I have a mechanism by which a JDK can read a list of classes that implement some service straight from the classpath, usually via a file in META-INF/services/fully.qualified.name.ServiceInterface which lists 1 fully qualified classname per line. Reading these files out is baked into the core: ServiceLoader. Making them - lots of utilities around that let you just annotate a class and an annotation processor makes the services file for you.
The java module system has its own take on this idea, using the provides keyword. I suggest you don't mess with the java module system, though. Nobody* uses it.
Factories
The way ServiceLoader forces you to work, but this way is quite sensible so you should do this too (handrolling your own ServiceLoader is a single page class, so if you want to deviate, you can - it won't be difficult, it's just a bad idea stylewise), is that the involved classes have the following rules:
They MUST implement/extend the service interface.
They MUST have a public no-argument constructor.
The SPI system will then instantiate the class once using that constructor and will then give you a list of the service interface.
If this 'no arguments' thing is bothering you, that's when you add in a single layer of abstraction: The 'service' describes a factory, the classes in the META-INF/services class file are implementations of the factory service, and the factory's job is to make the instances you actually want.
Example
Let's say we are an image editor and you want a pluggable 'find interesting objects using AI'.
You start by making an interface that describes an image filter:
public interface ThingieFinder {
/** Describe what this thingiefinder finds */
String getDescription();
/** Try to find stuff within a segment of the image */
List<Thingie> find(Coords coords, double howSeriously);
}
But what's missing in this description is the constructor which would, of course, take the object representing the entire image.
Factories are the answer. Make this interface too:
public interface ThingieFinderFactory {
public ThingieFinder make(Image image);
}
This interface 'represents' the constructor. An implementation of this factory can be a trivial one-liner:
public class FaceFinderFactory implements ThingieFinderFactory {
public FaceFinder make(Image image) {
return new FaceFinder(image);
}
}
and this factory has a single no-args public constructor! ThingieFinderFactory can be the service, and this can be an implementation of it.
*) Rounding down considerably, but it's far less than half and that doesn't appear to be changing.
Mulitple problems in your code
List does not have put method. Learn about List from here
Java does not support spread operator(...) like JavaScript. In Java (...) is used for varargs
One of many ways to handle your errors.
public A(Object ... args) {
}
List<Object> objects = new ArrayList<>();
objects.add(new Object());
objects.add(new Object());
A a = new A(objects);

Why Not Use Instance Objects Instead of ThreadLocal in Java? [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
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!

Why is ClassLoader created from specific class when holds global information? [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 7 years ago.
Improve this question
I just came to realise that this will sometimes return null (print null in console):
package myproject;
public class A {
public static void main(String[] args) throws Exception
{
System.out.println(A.class.getClassLoader().getResource("A.class"));
}
}
Even though the ClassLoader is created from A.class it has nothing to do with it. It will load resources from the currently running classpath.
I realised this when I was running Maven test classes which run, by default, in project/target/test-classes while the normal classes, like A above, are in project/target/classes/.
I think this is very confusing. Why don't we get something like Class.getClassLoader to make it obvious that this is a global thing? Also, since ClassLoader is useless, what do developers use to load resources relative to their projects? If you include .jar dependency it works, resources included.
First of all: two different classes can be loaded by different class loaders. So, when you do:
ClassLoader forA = A.class.getClassLoader();
ClassLoader forB = B.class.getClassLoader();
it is very much possible that
if (forA.equals(forB)) {
print equal
} else {
print not equal
}
will print not equal!
Therefore your idea of using a single global Class.getClassLoader() breaks immediately: as there isn't a single entity that this method call could possibly return.
And for the other part - about access resources ... have a look at this SO question.
Each class is associated with the class loader that loaded the class. It makes perfect sense to let Class have an getClassLoader instance method.
It's nothing "wrong" with having multiple different objects return the same object through a get method.
It's like having, say person.getAddress(). All persons in a family may return the same address, but that doesn't mean it makes sense to have a static Person.getAddress.

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.

package visibility [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Why use package visibility (the default), unless the class should be public in java
As Rostislav Matl said, it's useful for when you want to make something that doesn't form part of your package's interface.
As an example, imagine you have a package and it provides an interface and at least one concrete implementation of a service.
People who use this service are going to care about the interface you provide and use one of the concrete classes you provide but they aren't going to care about much else beyond that. Our service has to talk to a database and it needs to be able to map the result from database queries into its own data type (that form its contract).
I find that I regularly create package private helper classes that contain utility type methods or perform tasks like the mapping that we need. Default (package private) visibility is perfect for this because other classes inside your package can use these helpers but no-one outside the package can see them so you're free to change them whenever you like.
This is a an example using some code:
We have our interface:
public interface UsefulService {
Collection<DataThings> getThings(Identifier id);
}
...and our concrete implementation:
public class JdbcUsefulServiceImpl implements UsefulService {
//We can break the code for the mapping out into its own class
private Mapper mapper;
#Override
public Collection<DataThings> getThings(Identifier id){
DatabaseQueryResult queryResult = //Code to hit a database and return objects from that domain model
Collection<DataThings> result = mapper.mapFromDatabaseToServiceDomain(queryResult);
return result;
}
}
Then we have our mapper. We don't need anyone outside the package to care about the service works internally so we use package private visibility and we can have as many classes as we want to get the job done:
class Mapper {
Collection<DataThings> mapFromDatabaseToServiceDomain(DatabaseQueryResult queryResult){
//magic to map objects goes here
}
}
The benefit that we have is that we can always change this Mapper class however we want or delete it or create new package private classes and we know the only (immediate) effects we can cause are inside this package. By immediate effects I mean compiler errors and serious things like that. Obviously you could break your service if you change its behaviour but that's what your automated test suite is there to catch :P
My understaning is package/default access is for package internals, i.e. classes that do not form package interface, i.e. classes that should not be used outside the package.

Categories

Resources