In JProfiler, why does my object not show in the All Objects view? - jprofiler

I'm new to JProfiler. I've created a very simple test application. Here's a Main.java with a main method:
package com.example;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Example e = new Example(); //Gets gc'ed?
System.out.println(e.getMessage());
System.in.read();
System.exit(0);
}
}
Note that I pause until key-press. This way I'm sure the main scope does not end until I press a key, so I expect e to exist and not be garbage collected (please correct me if this assumption is incorrect). The Example class:
package com.example;
public class Example {
public String getMessage() {
String testString = "This is the test string. Press a key to exit.";
return testString;
}
}
I start the above application using the JProfiler Eclipse plugin. I've created a session that's based on the Full Instrumentation profile; I've removed the Java EE and JDBC specific probes and left the rest at defaults.
Now when the profiler starts, I go to the all objects view and I'd expect to find com.example.* classes, but I find none; why is that happening?
Ok, so maybe I can only find these objects when I use another view, like the Allocation call tree, so I enable Allocation Recording using the button in the view (it's disabled by default). It asks me to click on calculate allocation after that, which pops up a dialog. I accept the defaults and I'm presented with an empty view that auto-updates in eternal emptiness.
So then I try Heap Walker. It asks me to make a dump first. I get a dialog that provides me the option to "select recorded objects" which is default unselected. I leave it at defaults and am presented with an instance count view. However, my object is not findable in this Classes view I'm presented with.
So I suppose I'm doing something fundamentally wrong; What should I do to see my objects, and specifically the precise instance count of my objects?
UPDATE 1:
I've found a part of the problem. When the profiler window comes up, it presents you with the Session Startup dialog, where you can choose the profile and set various settings. There is a little section on the first tab called "Startup" which has a setting called "Initial recording profile", which by default is set to [no recordings]. When I leave this at its default, I cannot find the Example object. When I set it to "CPU recording" I can find my Example object in the All Objects view.
UPDATE 2:
I cannot find the object in Heap Walker. When I select com.example.Example in the All Objects view, I can right-click the object and choose (show object in Heap Walker). When I do so, Heap Walker tells me there's no such object on the heap! What gives?
UPDATE 3:
The com.example.Example object seems to show up sometimes, sometimes not. I cannot figure out why. Additionally, when it shows up, it will disappear from the All objects view, even though the main loop has not exited yet, even though the com.example.Example object should still be alive...
UPDATE 4:
It turns out e is garbage collected, regardless of scope ending on IBM's J9 JVM. See my answer to this which modifies main to invoke a second method after the key-press wait, which forces the object to remain alive.

I finally truly solved this mystery. It turns out I'm running IBM's J9 VM. Apparently, J9 garbage collection is quite a bit more aggressive: It will clean up e within the main scope if e is not going to be used within that scope anymore. I have verified that this specific behaviour does not happen with Oracle's JVM.
So long story short: on IBM J9, you cannot assume that objects stay alive within the scope of a block. On Oracle's JVM, at least by default, e is not garbage collected until after the block ends, regardless of further usage of e.
On IBM J9, when you want to force the object to stay in existence, there has to be a future usage of it. To prove this I modified Example.java to contain the following:
package com.example;
public class Example {
public String getFirstMessage() {
String firstTestString = "This is the first message: Hello!";
return firstTestString;
}
public String getSecondMessage() {
String secondTestString = "This is the second message: Goodbye!";
return secondTestString;
}
}
Then, in main I made sure to have an invocation of getSecondMessage() AFTER the wait-on-key-press (System.in.read()). This way, we know for sure that the GC cannot cleanup the object before main's scope ends because there's an invocation waiting in the future, happening right after the user presses a key. So Main.java looks like:
package com.example;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Example e = new Example();
System.out.println(e.getFirstMessage());
System.in.read();
System.out.println(e.getSecondMessage());
System.exit(0);
}
}
Profiling the above code regardless of CPU recording settings previously thought to be a factor in this will work as expected: the object stays alive because it cannot be garbage collected before the key is pressed.

This way I'm sure the main scope does not end until I press a key, so I >expect e to exist and not be garbage collected (please correct me if this >assumption is incorrect).
That is correct. The "Example" object will be held by a stack reference at that point and cannot be garbage collected. Both the "All objects" view and the heap walker will show this object.
I just tested your example and it works for me with both JProfiler 8.1.4 and JProfiler 9.0.2.
Use the "View->Find" action to search for "Example".

Related

iOS9 storyboard what is unhandled action (handleNonLaunchSpecificActions)?

I've noticed the following error popping up in the console when running my app on iOS 9 when using a storyboard. I'm using xCode7. Is this something I need to be concerned about?
-[UIApplication _handleNonLaunchSpecificActions:forScene:withTransitionContext:completion:] ** unhandled action -> <FBSSceneSnapshotAction: 0x176bfb20> {
handler = remote;
info = <BSSettings: 0x176a5d90> {
(1) = 5;
};
}
There is nothing wrong with your code. This is a logging message internal to Apple, and you should file a radar about it.
There are two hints that show that this is probably Apple's code:
The underscore leading the method name _handleNonLaunchSpecificActions:forScene:withTransitionContext:completion is a convention indicating that the method is private/internal to the class that it's declared in. (See this comment.)
It's reasonable to guess that the two letter prefix in FBSSceneSnapshotAction is shorthand for FrontBoard, which according to Rene Ritchie in "iOS 9 wish-list: Guest Mode" is part of the whole family of software related to launching apps:
With iOS 8, Apple refactored its system manager, SpringBoard, into several smaller, more focused components. In addition to BackBoard, which was already spun off to handle background tasks, they added Frontboard for foreground tasks. They also added PreBoard to handle the Lock screen under secure, encrypted conditions. [...]
I have no idea what the BS prefix in BSSettings is for, but
BS is shorthand for BackBoard Settings, and an analysis of this log message would indicate that it's not anything you did, and you should file a radar with steps to reproduce the logging message.
If you want to try and grab a stack trace, you can implement the category linked to here. Some would argue that overriding private API is a bad idea, but in this case a temporary injection to grab a stack trace can't be too harmful.
EDIT:
But, we still want to know what this action is. So I put a breakpoint on -[UIApplication _handleNonLaunchSpecificActions:forScene:withTransitionContext:completion] and started printing out register values and found a class called FBSceneImpl which had a whole bunch of information about my application:
We are able to find out which private method is called next (stored in the program counter, instruction pointer, register 15.)
I tried finding the un-handled FBSceneSnapshotAction referenced in the log, but no dice. Then, I subclassed UIApplication, and overrode _handleNonLaunchSpecificActions:forScene:withTransitionContext:completion. Now I was able to get at the action directly, but still, we don't know what it is.
Then, I looked at the FBSceneSnapshotAction again. Turns out it has a superclass called BSAction.
Then I wrote a tool similar to RuntimeBrowser and looked up all of the subclasses of BSAction. It turns out that there's quite a list of them:
The two method names we have (one from the log and one from the program counter on the devices) indicate that these actions are used under the hood for passing actions around the system.
Some actions are probably sent up to the app delegate's callbacks, while others are handled internally.
What's happening here is that there is an action that wasn't handled correctly and the system is noting it. We weren't supposed to see it, apparently.
AFAIK, the info above is related to iOS during snapshot the screen (i suppose for double click home multitask related behaviour).I deeply investigated my application and seems that it does not get any side behaviours. You can safely ignore it, for now.
You can use the following gist simple category to test yourself against the calls to the above function:
I have figured it out, it will happen when you have IBAction method declared in .h or .m file but you have not bind it to any control.
.m example:
- (IBAction)click:(id)sender{
}
but not assigned this method to any control in storyboard.
haven't find out why it happens in my app, but at least you can catch the exception, if you want to keep this from popping up in your log pane. It's not a solution, but it might give you more insight why it is happing by inspecting any of the arguments that are passed in the catch.
swift 2 version:
import UIKit
extension UIApplication {
func _handleNonLaunchSpecificActions(arg1: AnyObject, forScene arg2: AnyObject, withTransitionContext arg3: AnyObject, completion completionHandler: () -> Void) {
//whatever you want to do in this catch
print("handleNonLaunchSpecificActions catched")
}
}

Possibility to complete current statement with anonymous implementation

Is there a shortcut (or menu entry) in IntelliJ IDEA to complete the current statement with an anonymous implementation. To make this more understandable:
I type something like: view.setOnClickListener( and would now like a shortcut to get the completion to:
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
<<new caret position>>
}
});
Assuming that the setOnClickListener method would accept one parameter of type OnClickListener. I don't care if there are already implementations of OnClickListener I would just like the very basic type (or interface) that is expected as an anonymous inner class.
So do anyone know if there is a possibility for this in IntelliJ IDEA, without the need of typing new OnClickListener (with auto completion) yourself?
The only thing you have to do is to write:
view.setOnClickListener(new + Ctrl+Shift+Space
This will bring up a list of alternatives but since you used the Smart Type Code Completion (instead of Basic Code Completion which is Ctrl+Space) you will have the one that fits best at the top.
So now just press Tab and the rest will be filled in for you.
You save some writing but still have to at least write new in order for it to work.
Smart Type code completion filters the suggestion list and includes only those types that are applicable to the current context.

Eclipse call ViewPart saveState on View close

I have a Eclipse plugin that uses a view which extends ViewPart. ViewPart has a saveState method which requires an IMemento.
I added my code to saveState and the corresponding init method and it works. Unfortunately, saveState is only called if the entire workspace is shutting down. My view is not of such great importance that I can expect it to be opened the entire time. Hence, it would be cool if saveState would be called on view closure.
I found a view-part listener as mean to react on view closure, but what I do not get is where the IMemento comes from. Where do I get the memento object that is used on workspace closure? Or where do I have to store my own memento object to make the view part use it in the init method if the view is (re)opened?
#Override
public void saveState(IMemento memento) {
super.saveState(memento);
memento = memento.createChild(MEMENTO_GUI_STATE);
memento.putBoolean(MEMENTO_IS_FLAT, !isHierarchicalModeActive());
memento.putBoolean(MEMENTO_IS_CATEGORY_MODE_ACTIVE, comboViewer.isVisible());
}
This is my saveState - can I tell my view somehow tell to call it every time the view closes?
Take a look at this question in the Eclipse FAQ:
Storing view state is done in two commons ways, depending on whether
you want to store settings between workbench sessions or across
invocations of your view. The first of these facilities is found
directly on IViewPart. When the workbench is shut down, the method
saveState is called on all open views.
Another mechanism for persisting view state is the JFace
IDialogSettings facility. The advantage of dialog settings over the
view save/init mechanism is that you can control when settings are
persisted. The saveState method is called only if your view is open
when the workbench shuts down, so it is not useful for storing view
state when the view is closed by the user. Dialog settings, on the
other hand, can be changed and persisted whenever you want.
Go to this other question or to the Eclipse documentation itself for the settings mechanism.
Well this could be "a bit" ugly but nothing else came to my mind: store memento variable as a field variable, initialize it in your init(IViewSite site, IMemento memento) method, override dispose() and call saveState(IMemento memento) explicitely.
You can read and write your own XMLMemento from your org.eclipse.core.runtime.Plugin.getStateLocation() at any time you want. As #BelaViser mentioned, you could write your file in your IViewPart#dispose() method and read it in your view constructor.

Weird JavaCore IType cache problem

I'm developing a plugin that takes all enums in workspace that implements certain interface (IDomain) parses the code (Using AST) does some modification over the enum and marks it as processed with an annotation (#IDomainInfo).
For example, it takes someting like this:
public
enum SomeEnum implements IDomain {
// ...
}
And generates something like this:
public #IDomainInfo(domainId = 1)
enum SomeEnum implements IDomain {
// Some changes here...
}
The idea behind of the #IDomainInfo is that annotated enums have not to be processed anymore by the plugin.
Basically what I do to accomplish the task is to make a search with JavaSearch API to find all the enums implementing IDomain (easy task), and as result I get a list of IJavaElements (which are in fact instances of IType). Then I call a method that iterates through the resulting list and creates a new list of all the IType instances that are not annotated with #IDomainInfo and then process the resulting list: For each non annotated IType do some work, annotate the IType with the #IDomainInfo annotation (Using AST) and then save back the results to file (using IFile, so I can see the changes without refresh, and in fact, if I have the enum open in the editor I see it refreshed instantly :-)
All that works fine, but if I open an #IDomainInfo annotated enum (just for testing) then remove the #IDomainInfo, save the file (I'm sure) and then call the action that does all the job I've described before, when I get to the part that filters annotated IType from non annotated ones, code is something like this:
for (IType type : typeList) {
IAnnotation annotation = type.getAnnotation(“IDomainInfo”);
if (!annotation.exists()) {
// The annotation does not exist, so add the type to the
// list of elements to update and go on...
ret.add(type);
continue;
}
// Something else here...
}
Well, it results that for the file I've just saved the IType detects the annotation I've just removed as if it's still there. If I close and reopen eclipse all works normally.
Now, I've just checked and triple checked my code, so I'm sure that I'm not keeping a stale copy of the old IType unedited still with the annotation version (all my IType come from a fresh java search call every time I run the action).
So the question is, what might I be doing wrong? I mean, I've just read the JavaCore API many times to check If I might be using it wrong or if I have some conceptual flaw there but really I have no clue, it's like if eclipse would be caching the IType ignoring the changes I've just made in the editor :-/
If any one have an idea I would appreciate it a lot :-)
When or how is your plugin called ? Did you register a resource listener or is it a project builder or something else ? If it is called by a resource listener, your plugin may be reading the 'primary copy' for your IType, which has not been saved yet. Hence your changes are still in the Working Copy.

Explain ASP.NET Events

See Also:
understanding events and event handlers in C#
As a web dev, I don't typically have to get into building my own events for objects, since most are inherent in the page. However, now I'm into a pretty complex (web) project where I think I may have to use them. I just read a chapter out of Pro VB 2008 and the .NET 3.5 Platform regarding events, delegates and lambdas (ch. 11) and while I have a better idea of what's going on, I am still having trouble wrapping my mind around when exactly to use them and how to use them. I understand their implementation, but the example in the book is a bit contrived.
I was hoping someone with a bit more understanding on the subject of events could provide me with a really solid example.
For my real-world application, I'm trying to use an event that would let me know when an item (some class, named OrderItem) has been updated and perform actions based on whether or not it's been updated. I considered using a flag/boolean property, but I know this doesn't smell right, and it's high-time I learn about how to use events correctly.
Thanks a lot!
EDIT Ok, so I guess to clarify a bit, what is the point of calling an event when all it is doing is calling a method? Why not simply call the method? This isn't a duplicate either, as I'm talking conceptually and she wants to know about handlers specifically. Also, I want to know what the difference would be between using an event or a "flag" property. And what do people mean by "subscribe" to an event?
Lets say you had an elevator system, and the part that moves up and down is called the ElevatorCar. When a person pushes a button to go to the 5th floor, it would make sense for the ElevatorController to call the ElevatorCar.RequestToFloor(5) method. Now when the car actually arrives at the 5th floor, it makes sense for it to raise an event like ArrivedAtFloor, passing 5 as the argument. The ElevatorController class would subscribe to the ArrivedAtFloor event of the ElevatorCar class.
This is all becauase the ElevatorCar class doesn't "know" anything about the ElevatorController class, but the ElevatorController class does know about the ElevatorCar class. Therefore the ElevatorCar class is given instructions by means of Methods, and it notifies the outside world of stuff that happens by means of events.
Does that make any sense?
EDIT:
Ok, first, go read the excellent answer listed in the See Also link (assume you've done that). An event is basically an object saying "if you want me to call you whenever X happens, then register your method here". Registering an event handler with the event is "subscribing". This allows encapsulation. So you can write, for instance, your ElevatorCar class once, and use it many times by many other classes.
As for the difference between using an event, or just calling a method, you have to ask yourself, should the ElevatorCar know about the ElevatorController class. If ElevatorController calls ElevatorCar.GoToFloor(x), how could the ElevatorCar class "call back" to ElevatorController without storing a reference to ElevatorController? That means the call has to become ElevatorCar.GoToFloor(int floor, ElevatorController ctrlr). Then the ElevatorCar class eventually has to call ctrlr.ArrivedAtFloor(floor). But you get into a lot of complexities... what if there's more than one car? You probably have to call ctrlr.ArrivedAtFloor(floor, this). Passing around references to yourself isn't optimal.
As for just setting a property, how does the other class know to come and read the property? The only way is to poll the property over and over to check for it to change. You can solve this, of course, by implementing INotifyPropertyChanged, but then again you're back to events!
Events are a specific case of the Inversion of Control (IoC) pattern. The traditional control flow, the caller invokes a method on the callee (like you are suggesting). With IoC (and thus events), we change around the application control and instead of tell the callee what to do, we tell the callee to notify us when something we are interested in happens.
Consider the case of a Timer. I want to be notified every 5 seconds (say). I don't want to constantly poll the timer ("is it time yet? is it time yet? is it time yet?"). Instead, I want to invert the flow control of my application. I want to tell the timer: "When it's time, please tell me by calling this method." That way, control is "inverted", the callee is invoking a method on the caller!
Consider the following code ...
using System;
using System.Timers;
namespace TestTimer
{
class Program
{
static void Main(string[] args)
{
// create my timer.
var t = new System.Timers.Timer(1000);
// register for notification
// tell the timer, "when it's time, call TimerGoesOff method"
t.Elapsed += new ElapsedEventHandler( TimerGoesOff );
// start the timer
t.Start();
// wait
Console.ReadLine();
}
// this gets called when the timer goes off
public static void TimerGoesOff(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Time is " + e.SignalTime);
}
}
}
Rather than call a method on the Timer to ask when it will go off again (as you suggest), I tell it, "when you go off, call the TimerGoesOff" method. Now, instead of just waiting for the Timer to go off, I could do some work. Consider this code ...
using System;
using System.Threading;
using System.Timers;
namespace TestTimer
{
class Program
{
static void Main(string[] args)
{
// create my timer.
var t = new System.Timers.Timer(1000);
// register for notification
t.Elapsed += new ElapsedEventHandler( TimerGoesOff );
// start the timer
t.Start();
// do some work while timer is going
new Thread(() => DoWork()).Start();
Console.ReadLine();
}
// this gets called when the timer goes off
public static void TimerGoesOff(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Time is " + e.SignalTime);
}
public static void DoWork()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine( "Working ..." );
Thread.Sleep( 1000 );
}
}
}
}
Now, I get output something like ...
Working ...
The Time is 8/25/2009 1:05:59 PM
Working ...
Working ...
The Time is 8/25/2009 1:06:00 PM
Working ...
The Time is 8/25/2009 1:06:01 PM
Working ...
The Time is 8/25/2009 1:06:02 PM
The Time is 8/25/2009 1:06:03 PM
I have used the Timer.Elapsed Event to change the control flow of my application. I can go off and do work while "waiting" for the timer event to pulse. This is made possible by IoC and Events.
This is particularly visible (hehe) in User Interfaces. I don't want to keep asking "has the user done anything yet? has the user done anything yet?" (that's the way it used to be done way back when). Instead, I tell Controls for example, "when the user clicks you, let me know". That way, I can go off and do other great stuff and still be responsive to the user.