So I have been reading a tutorial on Android development, and I have come across something that I have never seen during my Java developing (mainly school work):
Thread th = new Thread() {
public void run() {
if (iotdHandler == null) {
iotdHandler = new IotdHandler();
}
iotdHandler.processFeed(); resetDisplay(
iotdHandler.getTitle(),
iotdHandler.getDate(),
iotdHandler.getUrl(),
iotdHandler.getDescription());
dialog.dismiss();
}
};
th.start();
Now the book says extend thread, and I kind of understand what its doing, in a sense, but it doesn't follow the usual way to extend a normal class in java like so:
public Class Dog extends Animal...
and then you can follow on and override methods and such. But my question is, what is it actually doing in making a reference to new Thread object, but at the same time creating a method right after it, and what I assume is overriding some sort of method in the Thread class? Since I do not know what it is called, I can't really search for it, so I apologize for the obvious question if it is one. Any help would be much appreciated.
Revise your Java books :) It's called an anonymous inner class and was originally introduced to facilitate Java GUI development (with AWT/Swing). Since Android UI development follows many of the same patterns, it is used quite often in Android.
What it does is instantiating a class in place (without defining it in a separate file, etc.), overriding some of its methods (int this case run()). You can also implement an interface this by if you provide implementations for all of its methods.
first of all, that is nothing Android specific. You can extend the same way in "normal Java". The reason for doing an class extend like that is to reduce classes, when this "class extension" is needed only once. In your example it would be the same to write
public class MyThread extends Thread
{
#Override
public void run() {
[...]
}
};
and later on:
MyThread thread = new MyThread();
thread.start();
So the advantage is, that you don't need to implement a class and instantiate it later on.
Related
My goal is to have a Queue of method calls contained in a class that extends Thread whose run method pops a method call off of the queue once every 15 seconds. This could be done in a shady way using Strings, ints, or chars in a mammoth switch case, but I was wondering if anyone else has a far more elegant solution to this issue.
Something that would look like this?
public class Potato extends Thread{
Queue<Methods> methodsQueue = new LinkedList<Methods>();
public Potato(){}
run(){
methodsQueue.poll();//This would execute a method
}
//Methods of this class...
}
You can use an interface to wrap the methods you want to call:
public interface MethodWrapper {
void execute();
}
public class Potato extends Thread{
Queue<MethodWrapper> methodsQueue = new LinkedList<>();
public Potato(){}
run(){
methodsQueue.poll().execute();
}
//Methods of this class...
}
This one liner (which is available in the Android API) gives you the same functionality you're trying to implement:
ScheduledExecutorService s = Executors.newScheduledThreadpool(numThreads);
If you need to run arbitrary methods using reflection, then submitting them to this service is as easy as wrapping each one in custom Runnable argument and calling s.schedule(Runnable,long,TimeUnit);
I can't think of a more elegant, less cumbersome solution to your problem (at least when using Java). And it comes with the benefit of having been tested and used as part of the core Java API since 2004. – #CodeBlind
How would you create a Class that whichever class extends the Class, methods are automatically invoked/called. Just edit my question if it sounds misleading. I'll just showcase some samples
Example 1:
In unity when you extend monobehavior your methods are automatically called. I don't know if I'm right.
public class MyController : MonoBehaviour {
void Start()
{
//Being Called Once
}
void FixedUpdate()
{
//Being Called every update
}
on libgdx
Game implements ApplicationListener {
#Override
public void render () {
//Called multiple times
}
}
As What I have Understand and Tried Implementing it my self
public abstract Test{
protected Test(){
onStart();
}
public abstract void onStart();
}
public class Test2 extends Test{
public Test2(){
}
#Override
public void onStart(){
//Handle things here
}
}
I'm sorry, but I still really don't know how it works or what you call this technique.
Especially in unity, when creating multiple controllers that extends Monobehavior, all that controllers method that been implemented are called. Who's calling this classes and methods? Some reference or books on this would be a great help.
Note: Please edit my title for the right term to use on this. thanks
I'm sorry, but I still really don't know how it works or what do you call this technique
In your Java example, the onStart method is said to be a hook or a callback method.
Wikipedia defines hooking as follows :
In computer programming, the term hooking covers a range of techniques used to alter or augment the behavior of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed between software components. Code that handles such intercepted function calls, events or messages is called a "hook"
Wikipedia defines a callback as follows :
In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback, or it might happen at later time as in an asynchronous callback
Any class that instantiates Test method from the Test class will result in the onStart method of the instance being called. Example :
Test test = new Test2();//calls onStart in Test2.
That being said, I am not sure who calls the methods in case of MonoiBehavior but your general understanding of how to implement a hook or a callback in Java is correct.
=== Conclusion ====
found a good read at https://softwareengineering.stackexchange.com/a/149569 which states
Current GC algorithms are actually optimized for creating many many small objects that are short lived,
So I think using anonymous inner class a lot in project would not be a big deal regarding to performance*
========================================================================
Because function is not the first class citizen in current Java(Java7), using anonymous inner class seems the only way to implement full async application.
I know it will bring larger memory footprint and burden garbage collector in some extent, but I don't know how serious it could be? Recently my colleague argued with me because my code was written in functional style by leveraging anonymous inner class, his objection was all about performance. Though I don't agree, I can't cite any example to prove myself. I know groovy is implementing closure all using anonymous class, but groovy does have poorer performance than java(of course anonymous should only take part of responsibility, as groovy heavily uses reflection as well).
so I wonder in real world, is there any project dropping anonymous class just because performance? how about UI framework like swing? Is it using anonymous class massively?
without anonymous, I can't imagine how to implement async elegantly in java. our project already uses a very ugly way to make class method work as function pointer. I hate that much and want to convince people anonymous class is the right way to go.
My Example:
// basically, I use Completion interface to make normal java methods work in async manner
public interface Completion {
void success();
void fail(String reason);
}
void methodA(Completion completion) {
do_some_business_by_calling_remote_service ....
when remote_service_ack_success:
completion.success();
else:
completion.fail(remote_service_error);
}
void methodB() {
methodA(new Completion() {
public void success() {
continue to do something;
}
public void fail(String err) {
handle error
}
});
}
There's basically two issues here, neither of them really have to do with the anonymous aspect. Anonymous classes aren't really any different than regular inner classes except that they don't have a name. An anonymous inner class gets compiled to a regular inner class, which in turn is still not really any different from a static nested class.
Issue 1 is that since they are inner, they keep a reference to the enclosing class:
class Outer {
interface Inner {}
Inner inner = new Inner() {
{
System.out.println(Outer.this);
}
};
}
This is not so much an issue and most of the time it's desired because you are doing something functional and want to use the outer instance's members inside the inner class. But it could create problems since as long as the inner class is alive, the outer class can't be garbage collected.
Issue 2 is that indeed they are an object so indeed your methodB is creating a new one each time it's called.
The obvious solution is just to create it once:
class MyProcess {
final Completion myCompletion = new Completion() {
#Override
public void success() {}
#Override
public void fail(String err) {}
}
void methodA(Completion c) {}
void methodB() {
methodA(myCompletion);
}
}
It seems like what you like is the syntax though and there's not really a solution to keep the syntax and not create an object at the same time.
My personal opinion: if you aren't calling this method a lot, I agree the syntax can be nice and clear. If you are calling it a lot, switch to a single object because you are crowding memory space. If it gets called 1000 times, that's 1000 objects. Object size differs by platform, but it's typically a minimum 8 or 16 bytes + a pointer to the outer instance. That's not a huge impact but it could, for example, prompt garbage collection to run which can cause subtle stalling.
By the way, I was thinking about this again and thought of the following idea:
Completion myLazyCompletion;
void methodB() {
methodA(myLazyCompletion != null ? myLazyCompletion :
(myLazyCompletion = new Completion() {
// overrides
})
);
}
I would say don't do that, but I thought it was interesting. : )
So I've stumbled across several ways of implementing an ActionListener and I'm wondering if someone can walk me through the differences of how each works and whether there are reasons or advantages to use one over the other?
The first is below in a block of code:
public void actionPerformed(ActionEvent arg0) {
// CODE HERE
}
The second way I saw was within another block of code as:
private class myListener implements ActionListener {
// CODE HERE
}
The third was is simply having a separate class for the ActionListener, with similar code to that above, but within a separate class.
I'm wondering whether the method approach is more efficient as new objects don't have to be created for each, you simply reference this as the ActionListener rather than, for example, referencing new myListener(). Thank you.
There's no difference in speed in any of the options; you'll always have an object that implements the ActionListener interface. Avoiding an instance of a separate class will just save you a few bytes of memory.
Your choice really should be based on what makes sense for your code, structurally. For example, having your public class implement ActionListener may look weird for those who are using that class, especially if the ActionListener behavior is supposed to be private to the class and not used outside it.
So it's mostly a choice of what you think looks better in your code; the only real difference will be with regards to field / method access (e.g. a separate, non-inner class won't have access to private methods and fields of your class, an anonymous inner class can't access non-final variables of the enclosing method, etc).
I don't like or use "implements ActionListener".
I do like and use anonymous inner classes like:
btnPurplescreen.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Color baseColor = Color.BLUE;
panelImage.setBackground(baseColor);
panelReference.setBackground(baseColor);
panelReference2.setBackground(baseColor);
baseType = BaseType.PURPLE;
}
});
You're stumbling in more ways that one.
In some sense, there is only one way to create a listener: there must be an object of a class that implements ActionListener, which means the class has the actionPerformed method.
There are three ways to do this:
You can modify a class you are already using for something else by marking it as implementing ActionListener and adding the actionPerformed method. This saves you creating a new class -- a savings of negligible value in most cases -- but mars otherwise perfectly good code. A few cases, when the existing
You can create a new named class. This is useful if you think the name is going to be meaningful to someone. If you are really using names like "MyListener", that's a clue that no, no-one cares about the name.
Finally, and usually, you can create an unnamed class. If all you want to do is add a fragment of code as a listener.
Whatever your choice, it's extremely unlikely to have any detectably effect on the time or memory performance of your finished system. The choice should be dictated by concerns about readability and maintainability.
Sorry for another vague example...but I have a single class where I'm starting a new thread instance. However, if I add a new thread instance, it interrupts (destroys?) the first.
But, if I run two instances of the class (separately, after I turn them into jar files) where each instance only opens up a single thread, they both run concurrently and fine.
I'm convinced the error is the way I'm implementing multi-threading.
Any suggestions for things to look for? Thanks! Sorry for the vague example.
You cannot assume that an arbitrary class is thread-safe.
Authors of a class should be explicit about the thread-safety of their classes, but it's very common that they do not. Given that environments such as Servlets may be intrinsically mulit-threaded this can be a real problem.
You need to study the class and discover which, if any, methods are thread safe. It is possible that the class InstanceOfClassIDontControl has static variables that are getting confused by multithreaded access. If you not only don't control the class, but can't even see its source then you are going to need the owners support.
Ok, here's an example:
public class driver {
public static void main(String args[])
{
Thread x;
Thread y;
x = new Thread(new pow());
y = new Thread(new pow());
x.start();
y.start();
}
}
public class pow extends Thread {
public void run() {
InstanceOfClassIDontControl a = new InstanceOfClassIDontControl();
a.doVariousProcesses();
}
}
In the example, I (obviously) don't control the class whose instance is created and called in the thread. Each thread may run for minutes. But whenever a concurrent thread is ran (in this case, with y.start()), it destroys the actions of the object called in the run() instance of x.start().