The following simple snippet grabs all the available screen devices in Java no problem:
GraphicsDevice[] gds = ge.getScreenDevices();
That much is simple. However, I'd like to get notified when this changes (an existing screen changes, one is removed, a new one is added, etc.)
I could just poll on the above method call which is do-able, but ideally I'd like a notification (observer pattern style) when something changes. I can't see a way in the API to hook onto such an event though.
Is this possible, either through plain JDK or an add-on library, or should I just resort to polling every other second or so?
From all the looking around I've done, the answer at present (looking at Java 7 and the currently proposed Java 8 APIs) is simply no - you just have to poll it seems.
Although this is nasty from an OO perspective from a performance perspective it doesn't really make a difference as long as you're sensible with intervals - it seems to be a very cheap operation. My approach was to do the polling in a separate class and provide an observer pattern on which others could register. Does the job well, all the polling is in one place and if a better API comes along later, it'd be trivial to swap out with the new interface.
Related
As far as I know Stream API is intended to be applied on collections. But I like the idea of them so much that I try to apply them when I can and when I shouldn't.
Originally my app had two threads communicating through BlockingQueue. First would populate new elements. Second make transformations on them and save on disk. Looked like a perfect stream oportunity for me at a time.
Code I ended up with:
Stream.generate().flatten().filter().forEach()
I'd like to put few maps in there but turns out I have to drag one additional field till forEach. So I either have to create meaningless class with two fields and obscure name or use AbstractMap.SimpleEntry to carry both fields through, which doesn't look like a great deal to me.
Anyway I'd rewritten my app and it even seems to work. However there are some caveats. As I have infinite stream 'the thing' can't be stopped. For now I'm starting it on daemon thread but this is not a solution. Business logic (like on connection loss/finding, this is probably not BL) looks alienated. Maybe I just need proxy for this.
On the other hand there is free laziness with queue population. One thread instead of two (not sure how good is this). Hopefully familiar pattern for other developers.
So my question is how viable is using of Stream API for application flow organising? Is there more underwather roks? If it's not recomended what are alternatives?
I am coming from Java but have been doing some Node.js lately, and have been looking at the EventEmitter module in Node.
What I don't understand is the fundamental difference between Event-driven programming and 'regular' programming.
Here is some psuedo-code to demonstrate my idea of "event-driven" programming.
EventEmitter ee = new EventEmitter();
Function f = new SpecialFunction();
ee.on('grovel',f);
ee.emit('grovel'); //calls function 'f'
the only work the EventEmitter object seems to be doing is creating a hash relationship between the String representation of an event (in this case 'grovel') and a function to respond with. Seems like that's it, not much magic there.
however, my question is - how does event-driven programming really work behind the scenes with low-level events like mouse-clicks and typing? In other words, how do we take a click and turn it into a string (like 'grovel') in our program?
Okay. I will take a run at this.
There are a couple of major reasons to use event emitters.
One of the main reasons is that the browser, which is where JavaScript was born, sometimes forces you to. Whether you are wiring your events straight into your HTML, using jQuery or some other framework/library, or whatever, the underlying code is still basically the same (erm, basically...)
So first, if you want to react to a keyboard or mouse event, like you mentioned, you could just hard bind directly to an event handler (callback) like this:
<div onclick="myFunc(this)">Click me</div>
...or you could do the exact same thing in JS by DOM reference:
document.getElementById('my_element').onclick = function (evt) {
alert('You clicked me');
};
This used to be the primary way we wired up click handlers. One lethal drawback to this pattern is that you can only attach one callback to each DOM event. If you wanted to have a second callback that reacted to the same event, you would either need to combine write it into the existing click handler or build a delegate function to handle the job of calling the two functions. Plus, your event emitter ends up being tightly coupled to the event listener, and that is generally a bad thing.
As applications became more complex, it makes more sense to use event listeners, instead. Browser vendors (eventually) settled on a single way to do this:
// Build the handler
var myHandler = function (evt) {
alert('You clicked me too');
window.myHandlerRef = this; // Watch out! See below.
};
// Bind the handler to the DOM event
document.getElementById('my_element').addEventListener('click', myHandler);
The advantage to this pattern is that you can attach multiple handlers to a single DOM event, or call one single event handler from several different DOM events. The disadvantage is that you have to be careful not to leak: depending on how you write them, event-handling closures (like myHandler above) can continue to exist after the DOM element to which they were attached have been destroyed and GCed. This means it is good practice to always do a removeEventListener('click', myHandler). (Some libraries have an off() method that does the same thing).
This pattern works well for keyboard events as well:
var giveUserAHeadache = function (evt) {
alert('Annoying, isn\'t it?');
};
document.addEventListener('keypress', giveUserAHeadache);
Okay. So that is how you usually handle native browser events. But developers also like to use this pattern of event delegation in their own code. The reason you would want to do this is so you can decouple your code as much as possible.
For example, in a UI, you could have an event emitted every time the user's browser goes offline (you might watch navigator.onLine for example). Maybe you could have a green/red lamp on your page header to show the online state, and maybe you could disable all submit buttons when offline, and maybe also show a warning message in the page footer. With event listeners/emitters, you could write all of these as completely decoupled modules and they still can work in lock-step. And if you need to refactor your UI, you can remove one component (the lamp, for example), replace it with something else without worrying about screwing up the logic in some other module.
As another example, in a Node app you might want your database code to emit an error condition to a particular controller and also log the error -- and maybe send out an email. You can see how these sorts of things might get added iteratively. With event listeners, this sort of thing is easy to do.
You can either write your own, or you can use whatever pattern is available in your particular environment. jQuery, Angular, Ember and Node all have their particular methods, but you are free to also build your own -- which is what I would encourage you to try.
These are all variations of the same basic idea and there is a LOT of blur over the exact definition or most correct implementation (in fact, some might question if these are different at all). But here are the main culprits:
Observer
Pub-Sub
Mediator
This is one of the questions that involves crossing what I call the "Hello World Gulf" I'm on the "Hello world" I can use SQLite and Content Providers (and resolvers) but I now need to cross to the other side, I cannot make the assumption that onUpgrade will be quick.
Now my go-to book (Wrox, Professional Android 4 development - I didn't chose it because of professional, I chose it because Wrox are like the O'Reilly of guides - O'Reilly suck at guides, they are reference book) only touches briefly on using Loaders, so I've done some searching, some more reading and so forth.
I've basically concluded a Loader is little more than a wrapper, it just does things on a different thread, and gives you a callback (on that worker thread) to process things in, it gives you 3 steps, initiating the query, using the results of the query, and resetting the query.
This seems like quite a thin wrapper, so question 1:
Why would I want to use Loaders?
I sense I may be missing something you see, most "utilities" like this with Android are really useful if you go with the grain so to speak, and as I said Loaders seem like a pretty thin wrapper, and they force me to have callback names which could become tedious of there are multiple queries going on
http://developer.android.com/reference/android/content/Loader.html
Reading that points out that "they ought to monitor the data and act upon changes" - this sounds great but it isn't obvious how that is actually done (I am thinking about database tables though)
Presentation
How should this alter the look of my application? Should I put a loading spinning thing (I'm not sure on the name, never needed them before) after a certain amount of time post activity creation? So the fragment is blank, but if X time elapses without the loader reporting back, I show a spiny thing?
Other operations
Loaders are clearly useless for updates and such, their name alone tells one this much, so any nasty updates and such would have to be wrapped by my own system for shunting work to a worker thread. This further leads me to wonder why would I want loaders?
What I think my answer is
Some sort of wrapper (at some level, content provider or otherwise) to do stuff on a worker thread will mean that the upgrade takes place on that thread, this solves the problem because ... well that's not on the main thread.
If I do write my own I can then (if I want to) ensure queries happen in a certain order, use my own data-structures (rather than Bundles) it seems that I have better control.
What I am really looking for
Discussion, I find when one knows why things are the way they are that one makes less mistakes and just generally has more confidence, I am sure there's a reason Loaders exist, and there will be some pattern that all of Android lends itself towards, I want to know why this is.
Example:
Adapters (for ListViews) it's not immediately obvious how one keeps track of rows (insert) why one must specify a default style (and why ArrayAdapter uses toString) when most of the time (in my experience, dare I say) it is subclasses, reading the source code gives one an understanding of what the Adapter must actually do, then I challenge myself "Can I think of a (better) system that meets these requirements", usually (and hopefully) my answer to that converges on how it's actually done.
Thus the "Hello World Gulf" is crossed.
I look forward to reading answers and any linked text-walls on the matter.
you shouldnt use Loaders directly, but rather LoaderManager
One of my coworkers would like my Swing app to adapt correctly to the removal of a 2nd display monitor.
Is there any way to get notification of this, other than polling to repeatedly compute virtual bounds? (per the code sample in http://download.oracle.com/javase/6/docs/api/java/awt/GraphicsConfiguration.html)
Hum, tricky one. Because GraphicsConfiguration class won't give us any listeners, I'll have only a couple of alternatives:
(If Windows) Use a JNI interface to
Windows to detect display settings
change and forward them to Java.
This would be the
SystemEvents::DisplaySettingsChanged
Event.
Create a simple polling Thread -
timer that retrieves the result of
Toolkit.getDefaultToolkit().getScreenSize()
as you've already stated before.
I have changed my app to use MVC and it has gotten pretty slow.
Description:
The application has a number of 5 composites, each composite represents different data and is not always showing
The app is using MVC and I am passing the model to each composite when an update occurs.
I am rebuilding a Tree (and all tree items) every time a notify is recieved, however, only one of the tree items would have changed, so this is possibly a waste.
Due to the style of the app I have to even notify() for insignificant things like changing the text in a text box or selecting a menu because I have a saved icon that turn to unsaved whenever something is changed in the tree Item.
All the composites are implementing the same Observer Interface, so all are getting updated on every notify().
Can someone give me some tips on what I should do to speed this app up. Which of the above might be more CPU hungry than others, ie, is rebuilding a Tree with < 20 items on every notify() going to use that much CPU time, do I need to re-design this? Should I create a seperate interface such as SaveStateChanged that will only notify the tree, or is this just a waste of time.
When an application is getting slow, then most time is often not spent performing the JavaScript calculations themselves (e. g. I don't believe, that just calling a lot of observers is a problem - it depends on what they do!). Very often, slowness is caused by things like redundant layout (e. g. when each of the observers causes a layout call). Sometimes, lots of DOM manipulations can also be a problem (mainly with Internet Explorer).
I would suggest to play a little bit with Speed Tracer, especially the redundant layout example. If that's not the specific problem in your application, you should be able to take a similar approach as shown in the example to track it down. Use markTimeline("String") to make special parts of your code show up clearly in Speed Tracer's graphs.
The first step you need to take is to isolate exactly where the performance problem is occurring. You've identified some good possible candidates, but you'll want to back that up with cold hard stats.
You may find you only need to address one of the above points, or that there might be another sticking point entirely
I suggest you get rid of the Observer interface in favour of something more finegrained. Look at the MVC architecture in Swing where a JTree is associated with a TreeModel and implements TreeModelListener interface to hear of changes to the model. The TreeModelListener interface has specific methods called by the model to indicate nodes changing, being added or removed from the tree. In addition it has a TreeModelEvent which provides even more data about which nodes are affected. If the model tells you precisely what has changed you will have a lot more scope for reacting intelligently from your listener implementations.