How to detect how much handles the application is using - java

For our SWT-based application we are getting relatively often the SWT error "no more handles". To detect whether the problem is in our code, how to detect - using code in our application - how much handles our application actually is using?

If I understand you correctly, you are probably getting the following exception:
org.eclipse.swt.SWTError: No more handles
You may be creating resources (such as Font, Image or GC objects) that you aren't correctly disposing.You might want to take a moment to read through SWT guide on Managing Operating System Resources.
To determine if this is indeed the case, I can recommend this useful article: Diagnosing Handle Leaks in SWT/RCP Windows Applications.
Use Sleak, it is also a way to monitor your resources.

In the "Processes" tab of the Windows Task Manager you can add the "Handles" column, showing the handles all your process use in real time.

Baz' tip for Sleak gave me the idea:
final DeviceData data = new DeviceData();
data.tracking = true;
display = new Display(data);
and then in regular intervals I log the number from
final int handleCount = display.getDeviceData().objects.length
Unfortunately, detecting the number of widgets (I guess, they are using handles, too) is not possible so easily.

Related

How do I find the name of the program that would launch a given file?

I am looking for a way to find the name of the program (in my code) that will launch when an operating system tries to open a given file. I will not be launching the application I'm just looking for its name. Ideally the routine I'm looking for/building would take a filename and return a string. I am programming in Java 8 on Eclipse and need my jar file to stay cross platform.
Simplest solution I can find is to use SWT's class 'Program'. Although this assumes that I can correctly identify filetype which is another big can of worms I'm not going to into here.
String ext = extractFileType(filename);
Program p2 = Program.findProgram(ext);
if (p2 != null) programName = p2.toString();
But for a number of reasons I DON'T WANT TO USE the SWT library if at all possible. I'm using Swing and and I really don't want my clients to need to download a different application (jar) dependent on their operating system. I'm well aware that the underlying code is operating system/Window Manager dependent.
Anyone know of any other package besides SWT that already does this? I can't find one. Or similar enough I can strip the results to get what I want? Even if it's only for one platform? I'm experimenting with Apache Tika but I don't see anything helpful there.
Any hints on where to look to start write this myself? I know this entails reading the registry on Windows. I need this code to work on the most recent versions of Windows, and OS X. And eventually Linux but Linux windowing systems are not a priority.
Is there a way to link/load SWT in Eclipse to make the cross-dependent part of using SWT this code a little more lightweight and invisible to the end user? I'm not new to coding but am to using Eclipse.
Here is a quick description of my solution. I did a fair amount of hunting around and I deciding on simply using the JNA library. https://github.com/java-native-access/jna and writing my own native library on a Macintosh to get it to work.
Windows: Fairly straight forward usage of JNA. I'm calling FindExecutable & PathFindExtension from JNA.
public interface MyShell32 extends Shell32 {
MyShell32 INSTANCE = (MyShell32) Native.loadLibrary("shell32", MyShell32.class, W32APIOptions.DEFAULT_OPTIONS);
WinDef.HINSTANCE FindExecutable(String lpFile, String lpDirectory, char[] lpResult);
}
{
...
char[] returnBuffer = new char[WinDef.MAX_PATH];
shell.FindExecutable(filename, null, returnBuffer);
app = Native.toString(returnBuffer);
...
}
PathFindExtention() call is similar but returns a pointer so it's more straight forward.
Macintosh: I tried all sorts of things and finally decided to write my own tiny native library to call in objective C
rtnValue = [[NSWorkspace sharedWorkspace] getInfoForFile:filenameNS
application:&AStr
type:&TStr];
This library is tiny (but I may add to it if I need other native calls) but I need to write a C/C++ shell as well as the Objective C to get it to work. I then call this library JNA. Not that different from writing straight JNI but I found it easier to code.
public interface NSWWraper extends Library {
/** The instance **/
NSWWraper INSTANCE = (NSWWraper) Native.loadLibrary("NSWWraper", NSWWraper.class);
// CP_NSWWraper
Pointer FindFileInfo(String filename);
void FreeMem(Pointer memory);
}
I honestly haven't tested this calling this a large number of files so I don't know how much it slows down my code. JNA calls are supposed to be expensive. It's interesting timing on someone asking for my solution as I'd had to put this on back burner and only got it working on Windows yesterday. I was going to incorporate this into the rest of my project today.
Edited to add. I didn't use JINI because I found it's not being very well supported on a Macintosh anymore and JNA was the better solution for Windows and I had to use it anyway.

Why use getResourceAsStream when loading images?

Let's say I'm creating a jar file and have an icon in an asset folder to be included in the jar.
So before using, stage.getIcons().add(icon); in my code is there any particular advantage or disadvantage to having the icon as
Image icon = new Image("Assets/Icon.png");
Vs.
Image icon = new Image(getClass().getResourceAsStream("Assets/Icon.png"));
Both seem to work fine, so I'm looking to pinpoint which I should generally gravitate towards and why.
There's a related topic here but it compares loading styles mostly with web applications.
javafx.scene.Image(String) calls validateUrl, which does additional processing of the String value, including checking the current Threads contextClassLoader for the resource.
The advantage of using something like Class#getResourceAsString is you've already made the decisions for the class, which would be (slightly) faster, but also less ambiguous and would probably be easier to diagnose should you have issues (as you control the source mechanism for the image itself) and aren't leaving the decision making up to code that you don't immediately control (and since validateUrl is private static, can't change)

Strange phenomenon: Java/Swing-operations cause access violation in native library (JNA)

Greetings fellow developers!
Since SO was almost always helpful with my programming problems, I decided to sign up and give it a shot with my most recent problem. It really is a strange phenomenon that neither I nor my collegue can figure out. I'm sorry I can't provide a working sample, but the project is way to complex to break it down, and specific hardware is needed to run it properly. So I'll try my best to explain it.
The foundation of our project is a native library (a 32-Bit Windows C-DLL in this case) to access project-specific hardware via a Java application (JNA). The purpose is to manage and display the proprietary file-system of the hardware (connected via USB) in a Swing UI. This is a pretty common project configuration for us, since we integrated a lot of native libraries and drivers in Java applications.
Summary: Unit-tests for enumerating devices work fine. A module of the native library allocates memory and fills it with structs, each containing information for a connected device. It is not good practice, but since we do not have any influence on this part we have to go with it. I mapped this struct in Java/JNA, call the native function, copy the struct content to a Java transfer class and print it in the console. Works just fine.
Now if there are UI-operations active while enumerating devices, the native library crashes with an access violation. Even if this UI-operations have nothing to do with the library. The JNA error message shows an EXCEPTION_ACCESS_VIOLATION (0xc0000005), which SO research revealed as invalid/empty memory.
Has anyone ever encountered such problems before? We certainly never did. It took me days to narrow down the error source to this part of the code. Debugging is not easy when native libraries are involved.
Is it possible that there is a JVM memory concurrency problem? Since the native library allocates memory by itself and the JVM doesn't know anything about it - so the JVM tries to allocate memory for new Swing components in already used memory?
Code:
The following snippet is from my unit-test, broken down as far as possible. The intended sequence is obvious: Remove nodes from the root-node, load connected devices and add these devices as new nodes. This code crashes with an access violation, but NOT AT THE NATIVE CALL - it crashes as soon as I access tree components.
public void loadDevices(){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
rootNode.removeAllChildren();
rootNode.add(new LoadingNode());
tree.expandPath(new TreePath(rootNode));
}
});
final List<Device> devices = lib.loadDevices(); // wrapped native call
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
rootNode.removeAllChildren();
if(!devices.isEmpty()){
for (Device dev : devices ) {
DevNode node = new DevNode(dev);
rootNode.add(node);
}
}
}
});
}
Note: The DevNode does not contain any native data, the content of each native struct is copied to a Java transfer object. The GC should not have issues when trying to move object data, because all unmanaged code is handled locally in the lib#loadDevices() method.
When I remove the calls to the SwingUtilities completely and print the resulting device information to the console instead of creating nodes, this part works fine.
As soon as I try to access the JTree or TreeModel members, the code crashes. It doesn't metter if I do this in a call to SwingUtitilies#invokeLater() or in the same thread.
I know this is a very specific problem that hardly anybody would be interested in (what makes it really hard to search for solutions in SO/Google). But maybe I am lucky and somebody has already encountered this problem.
So long
xander
Edit: Originally this code was wrapped in a worker thread, leading to the same results. This is just a snippet of my unit-test.
Edit 2: It seems I didn't make myself clear enough or forgot to mention something important here, sorry. The access to the tree or its model doesn't necessarily have to do with the native library. Look at the code again: The first call to invokeLater does nothing but remove nodes from the tree. Even when I remove the second call to invokeLater, the native library crashes!
I have struggeled a lot with JTree untill I learned this:
On JTree one should not edit the nodes itself, but use the methods provided on the DefaultTreeModel:
setRoot(TreeNode root)
removeNodeFromParent(MutableTreeNode node)
insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index)
Editing the nodes itself can (and will sooner or later) lead to strange behaviour.
This ofcourse when you are using DefaultTreeModel and MutableTreeNode. I would strongly advise to do this as I have seen to many wrong implementations of TreeModel.
final List<Device> devices = lib.loadDevices();
(by assuming that your code by using JNA is able to returns each node separatelly or collection of List<Device>'s one time if ended) should be called from Worker Thread, e.g. Runnable#Thread or SwingWorker
all output from to Worker Thread add to the DefaultTreeModel directly (or by creating a new MutableTreeNode) should be wrapped into invokeLater
no idea whats happens withut posting an SSCCE (List<Device>'s could be list of USB ports), short, runnable, compilable, just about JTree, is Model, and JNI/JNA ...

java: any way to detect changes in display configuration?

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.

Building a Java based stock trading application, need pointers for technologies to use

I am building an application in Java (with a jQuery frontend) that needs to talk to a third party application. it needs to update the interface every two seconds at the most.
Would it be a good idea to use comets? If so, how do they fit into the picture?
What other means/technologies can I use to make the application better?
The application will poll stock prices from a third party app, write it to a database and then push it to the front end every second, for the polling, I have a timer that runs every second to call the third party app for data, I then have to display it to the front end using JSP or something,
well at this point im not sure if I should use a servlet to write this out to the front end, what would you recommend? how should I go about it?
is there any new technology that I can use instead of servlets?
I am also using Berkeley db to store the data, do you think its a good option? what would be the drawbacks, if any for using berkeley..
im absolutely clueless so any advice will be much appreciated.
Thanks!
edit : I am planning to do this so that a deskop app constantly polls from the thrid part and writes to the database and a web app only reads and displays from the database, this will reduce the load on the web app and all it has to do is read from db.
Take a look at using a web application framework instead of Servlets - unless it's a really basic project with one screen. There are lots in the Java world unfortunately and it can be a bit of a minefield. Stick with maybe SpringMVC or Struts 2, the worst part is setting these up, but take a look at a sample application plus a tutorial or two and work from there.
http://www.springsource.org/about
http://struts.apache.org/2.x/index.html
Another option to look at is using a template framework such as Appfuse to get yourself up and running without having to integrate a lot of the framework together, see:
http://appfuse.org/display/APF/AppFuse+QuickStart
It provides you with a template to setup SpringMVC with MySQL as a database plus Spring as an POJO framework. It may be a quick way to get started and up and building a prototype.
Judging by your latency requirement of 2 seconds it would be wise to look at some sort of AJAX framework - JQuery or Prototype/Scriptaculous are both good places to start.
http://jquery.com/
http://www.prototypejs.org/
In terms of other technoloqies to make things better you will want to consider a build system, Ant/Maven are fine with Maven the slightly more complex of the two.
http://ant.apache.org/
http://maven.apache.org/download.html
Also, consider JUnit for testing the application. You might want to consider Selenium for functional testing of the front end.
http://www.junit.org
http://seleniumhq.org/
Is this really a stock trading application? Or just a stock price display application? I am asking because from your description it sounds like the latter.
How critical is it that data is polled every second? Specifically would it matter if some polls are a second or two late?
If you are building a stock trading application (where the timing is absolutely critical), or if you cannot afford to be delayed on your polling, I'd recommend you have a look at one of the Java Real Time solutions:
Sun Java Real-Time System (http://java.sun.com/javase/technologies/realtime/index.jsp)
WebSphere Real Time (http://www-01.ibm.com/software/webservers/realtime/)
Oracle JRockit Real Time (http://download.oracle.com/docs/cd/E13150_01/jrockit_jvm/jrockit/docs30/index.html)
Other than that, my only advice is that you stick to good OO design practices. For instance, use a DAO to write to your database, this way, if you find that Berkeley DB isn't quite for you, you can switch to a relational database system with relative ease. It also makes it easy for you to move on to some database partitioning solutions (e.g., Hibernate Shards) if you decide you need it.
While I may have my own technology preferences (for instance, I'd choose Spring MVC for the front end as others have mentioned, I'd try and use Hibernate for persistance), I really cannot claim that these would be better than other technologies out there. Go with something you are familiar with, if it fits the bill.
I think you should focus on your architectural design before picking technologies with a focus on scalability and extendability. Once an architectural design is in place you can look to see what's available and what you need to build, all of which should be pretty obvious.
While not directly comparable look at how Google, eBay and YouTube deal with the scalability problems they face. While a trading system won't have the issues these guys have with sheer numbers of users, you'll get similar problems with data volumes and being able to process price ticks in a timely fashion.
The LSE has getting on for 3000 names, multiply this by the 10 or so popular exchanges round the world and you've got a lot of data being updated continuously over the period each market is open. To give you an idea of what involved in capturing data from a single exchange take a look at http://kx.com/.
From a database perspective you've going to need something industrial strength that allows clustering and has reliable replication - for me this means Oracle. You also want to look at a Time-series Database Design, which in my experience is the best way to build this sort of system.
The same scaling and reliability requirements will apply to your app servers, with JBoss being the logical choice there, although I'd also consider the OSGi Spring Server (http://www.springsource.com/products/dmserver) as its lightweight nature could make it faster.
You'll also want Apache servers for load balancing and to serve static content - a quick Google will turn up stacks of information on that so I won't repeat it here.
Also forget polling, it doesn't scale. Look at using messaging and consumer processes for the cross-process communication, events and worker threads for the in-process communication. Both techniques achieve a natural load balancing effect that can be tuned by increasing the number of consumer processes or worker threads as need be.
Also a static front-end isn't going to cut the mustard, IMHO. Take a look at what's out in the market already - CNC Markets, IG Index, etc all have pretty impressive real-time trading apps.
As an aside, assuming this is a commercial project and not meaning to put a downer on the whole thing, companies like CNC Markets, IG Index, etc make their money from trading fees, the software being a means to an end, which you get access to for free simply by having an account. The other target for the trading software is commercial institutions such as the banks, investment managers, etc. I'd want a pretty watertight plan for how I was going to break into either of these markets before expending too much time and effort.
PostgreSQL is probably the right database. It's a little more enterprisy than MySQL. As for the front-end, there's lots of stuff that can go "on top" of servlets, SpringMVC, Tapestry, and so on and so forth. The actual servlet implementation will be hidden from you.
Many will suggest, and it's probably not a bad suggestion to use Spring to configure the application and to do any dependency injection.
If you're looking for something a little more lightweight, you might consider grails. It's quick to develop with and becoming mature.
Really though, it's kind of hard to recommend things without knowing what kind of "production" environment this would be. Are we talking lots of transactions? (sure, it's a stock trading program, but is it a simulation with a small number of users etc...) It's fun to suggest things, but if you're serious, I'm not sure I would start a major project like this. There are lots of ways to do this, and lots of ways to do this wrong.
Your intention is to build a web UI which shows realtime data eg: time, market data etc...
One of the technologies I have personally used is Web Firm Framework, an opensource framework under Apache License 2.0. It is a java server side framework to build web UI. For each and every tag & attribute there is a corresponding java class. We are just building the UI with Java code instead of pure HTML and JavaScript. The advantage is whatever changes we are making in the server tag & attribute objects will be reflected to the browser page without any explicit trigger from the client. In your case we can simply use ScheduledExecutorService to make data changes in the UI.
Eg:
AtomicReference<BigDecimal> oneUSDToOneGBPRef = new AtomicReference<>(new BigDecimal("0.77"));
SharedTagContent<BigDecimal> amountInBaseCurrencyUSD = new SharedTagContent<>(BigDecimal.ZERO);
Div usdToGBPDataDiv = new Div(null).give(dv -> {
//the second argument is formatter
new Span(dv).subscribeTo(amountInBaseCurrencyUSD, content -> {
BigDecimal amountInUSD = content.getContent();
if (amountInUSD != null) {
return new SharedTagContent.Content<>(amountInUSD.toPlainString(), false);
}
return new SharedTagContent.Content<>("-", false);
});
new Span(dv).give(spn -> {
new NoTag(spn, " USD to GBP: ");
});
new Span(dv).subscribeTo(amountInBaseCurrencyUSD, content -> {
BigDecimal amountInUSD = content.getContent();
if (amountInUSD != null) {
BigDecimal oneUSDToOneGBP = oneUSDToOneGBPRef.get();
BigDecimal usdToGBP = amountInUSD.multiply(oneUSDToOneGBP);
return new SharedTagContent.Content<>(usdToGBP.toPlainString(), false);
}
return new SharedTagContent.Content<>("-", false);
});
});
amountInBaseCurrencyUSD.setContent(BigDecimal.ONE);
//just to test
// will print <div><span>1</span><span> USD to GBP: </span><span>0.77</span></div>
System.out.println(usdToGBPDataDiv.toHtmlString());
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(1);
Runnable task = () -> {
//dynamically get USD to GBP exchange value
oneUSDToOneGBPRef.set(new BigDecimal("0.77"));
//to update latest converted value
amountInBaseCurrencyUSD.setContent(amountInBaseCurrencyUSD.getContent());
};
ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(task, 1, TimeUnit.SECONDS);
//to cancel the realtime update
//scheduledFuture.cancel(false);
For displaying time in real-time you can use SharedTagContent<Date> and ContentFormatter<Date> to show time in specific timezone. You can watch this video for better understanding. You can also download sample projects from this github repository.

Categories