on trying to monitor object sizes, string objects are not shown in the profiled results.
Can anyone tell me wat is the procedure to make them shown in results....
public class calling extends called {
called myobj3 = new called();
called myobj4 = new called();
public void function() {
myobj3.d="Plz";
myobj3.e="Help";
myobj4.d="Thank";
myobj4.e="You";
myobj3.act();
myobj4.act();
}
public static void main(String [] args) {
System.out.println("calls an object from called.java");
calling obj = new calling();
obj.function();
}
}
class called {
public String d;
public String e;
public void act() {
System.out.println(d+e);
}
}
memory profile Retained size Shallow Size
[Unreachable] called 40 40
[Unreachable] called 40 40
Perhaps, your objects have been collected or scheduled for collection (unreachable). In which point do you capture memory snapshot?
Disclaimer: I'm a YourKit developer.
Related
when i run my code in console i find this massage: Process is terminating due to StackOverflowException.
public class MyDictionary< TKey, Tvalue> : Dictionary<TKey,Tvalue>
{
private MyDictionary<TKey, Tvalue> md;
public MyDictionary(int size)
{md = new MyDictionary<TKey, Tvalue>(size);}}
static void Main(string[] args)
{var sOn = new MyDictionary<int, string>(4);}
when i use debug mode i find the problem in the constructor but i don't know
what is the problem?
Your MyDictionary class contains an instance of a MyDictionary. The constructor initializes this member, which in turn calls the constructor on that member, which has its own member, and so on until you exhaust the call stack and get the exception.
You probably don't need this member, but need to pass the size argument to the base constructor:
public class MyDictionary<TKey, Tvalue> : Dictionary<TKey, Tvalue>
{
public MyDictionary(int size) : base(size) {}
// Here ------------------------^
static void Main(string[] args)
{
var sOn = new MyDictionary<int, string>(4);
}
}
I tried to understand how it works but i am very slow with this(( so i decided ti ask here. In my prohramm i have static public class with different variables arrays, tabControls, Sizes, Pens an so on. But i need to set and get values of the variables from different threads how could i do it?
i have a class
public static class GLOBAL_STATIC_DATA
{
//.....
private static Size _get_Active_Project_ViewPort_Size()
{
//.....
}
public static Size Active_Project_ViewPort_Size
{
get
{
return _get_Active_Project_ViewPort_Size();
}
}
public static int Get_Panorama_Original_Image_Width()
{
}
public static TabControl MainTab = new TabContol();
public static int someInt = 100;
}
I need to write and to read all of that from different threads, could somebody help how shoud i change this static class to be able do that.
You just precede the public static entries with the class name...for example:
Size sz = GLOBAL_STATIC_DATA.Active_Project_ViewPort_Size;
In an attempt to solve this problem, I built a (very) small project that is reproducing part of it. It is a NetBeans project using Glassfish v2.1.1 and OpenJpa-1.2.2.
Globally, the goal is to be able to reload dynamically some business code (called 'tasks') without the need to (re)make a full deployment (eg via asadmin). In the project there are two of them: PersonTask and AddressTask which are simply accessing some data and printing them out.
In order to do that, I've implemented a custom class loader that read the binary of class files and inject it via the defineClass method. Basically, this CustomClassLoader is a singleton and is implemented like this:
public class CustomClassLoader extends ClassLoader {
private static CustomClassLoader instance;
private static int staticId = 0;
private int id; //for debugging in VisualVM
private long threadId; //for debugging in VisualVM
private CustomClassLoader(ClassLoader parent) {
super(parent);
threadId = Thread.currentThread().getId();
id = staticId;
++staticId;
}
private static CustomClassLoader getNewInstance() {
if (instance!=null) {
CustomClassLoader ccl = instance;
instance = null;
PCRegistry.deRegister(ccl); //https://issues.apache.org/jira/browse/GERONIMO-3326
ResourceBundle.clearCache(ccl); //found some references in there while using Eclipse Memory Analyzer Tool
Introspector.flushCaches(); //http://java.jiderhamn.se/category/classloader-leaks/
System.runFinalization();
System.gc();
}
ClassLoader parent = Thread.currentThread().getContextClassLoader();
instance = new CustomClassLoader(parent);
return instance;
}
//...
}
//this class is included in the EAR like a normal class
public abstract class AbstractTask {
protected Database database; /* wrapper around the EntityManager, filled when instance is created */
public abstract void process(Integer id);
}
//this one is dynamically loaded by the CustomClassLoader
public class PersonTask extends AbstractTask {
#Override
public void process(Integer id) {
//keep it empty for now
}
}
In my EJB facade (EntryPointBean), I simply do a lookup of the class, create a new instance of it and call the process method on it. The code in the project is slightly different, but the idea is quite the same:
CustomClassLoader loader = CustomClassLoader.getNewInstance();
Class<?> clazz = loader.loadClass("ch.leak.tasks.PersonTask");
Object instance = clazz.newInstance();
AbstractTask task = (AbstractTask)instance;
/* inject a new Database instance into the task */
task.process(...);
Until now, all is fine. If this code is run many times (via ch.leak.test.Test), there will be only one single instance of the CustomClassLoader when a heap analysis is done, meaning the previous instances have been successfully collected.
Now, here is the line triggering a leak:
public class PersonTask extends AbstractTask {
#Override
public void process(Integer id) {
Person p = database.getEntity("SELECT p FROM Person p WHERE p.personpk.idpk=?1", new Long(id));
//...
}
}
This simple access to the database has a strange consequence: the first time the code is run, the CustomClassLoader being used will never be garbage collected (even without any GC roots). However, all the further CustomClassLoader created won't leak.
As we can see in the dump below (done with VisualVM), the CustomClassLoader with instance id 0 is never garbage collected...
Finally, one other thing I've seen when exploring the heap dump: my entities are declared twice in the PermGen and half of them have no instances and also no GC root (but they are not linked to the CustomClassLoader).
It seems that OpenJPA has something to do with those leaks... but I don't know where I can search for more information of what I'm doing wrong. I have also put the heap dump directly in the zip with the project.
Does anyone have an idea ?
Thanks !
Consider the following existing classes which uses MEF to compose Consumer.
public interface IProducer
{
void Produce();
}
[Export(typeof(IProducer))]
public class Producer : IProducer
{
public Producer()
{
// perform some initialization
}
public void Produce()
{
// produce something
}
}
public class Consumer
{
[Import]
public IProducer Producer
{
get;
set;
}
[ImportingConstructor]
public Consumer(IProducer producer)
{
Producer = producer;
}
public void DoSomething()
{
// do something
Producer.Produce();
}
}
However, the creation of Producer has become complex enough that it can no longer be done within the constructor and the default behavior no longer suffices.
I'd like to introduce a factory and register it using a custom FactoryAttribute on the producer itself. This is what I have in mind:
[Export(typeof(IProducer))]
[Factory(typeof(ProducerFactory))]
public class Producer : IProducer
{
public Producer()
{
// perform some initialization
}
public void Produce()
{
// produce something
}
}
[Export]
public class ProducerFactory
{
public Producer Create()
{
// Perform complex initialization
return new Producer();
}
}
public class FactoryAttribute : Attribute
{
public Type ObjectType
{
get;
private set;
}
public FactoryAttribute(Type objectType)
{
ObjectType = objectType;
}
}
If I had to write the "new" code myself, it may very well look as follows. It would use the factory attribute, if it exists, to create a part, or default to the MEF to create it.
public object Create(Type partType, CompositionContainer container)
{
var attribute = (FactoryAttribute)partType.GetCustomAttributes(typeof (FactoryAttribute), true).FirstOrDefault();
if (attribute == null)
{
var result = container.GetExports(partType, null, null).First();
return result.Value;
}
else
{
var factoryExport = container.GetExports(attribute.ObjectType, null, null).First();
var factory = factoryExport.Value;
var method = factory.GetType().GetMethod("Create");
var result = method.Invoke(factory, new object[0]);
container.ComposeParts(result);
return result;
}
}
There are a number of articles how to implement a ExportProvider, including:
MEF + Object Factories using Export Provider
Dynamic Instantiation
However, the examples are not ideal when
The application has no dependencies or knowledge of Producer, only IProducer. It would not be able to register the factory when the CompositionContainer is created.
Producer is reused by several applications and a developer may mistakenly forget to register the factory when the CompositionContainer is created.
There are a large number of types that require custom factories and it may pose a maintenance nightmare to remember to register factories when the CompositionContainer is created.
I started to create a ExportProvider (assuming this would provide the means to implement construction using factory).
public class FactoryExportProvider : ExportProvider
{
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition,
AtomicComposition atomicComposition)
{
// What to do here?
}
}
However, I'm having trouble understanding how to tell MEF to use the factory objects defined in the FactoryAttribute, and use the default creation mechanism if no such attribute exists.
What is the correct manner to implement this? I'm using MEF 2 Preview 5 and .NET 4.
You can make use of a property export:
public class ProducerExporter
{
[Export]
public IProducer MyProducer
{
get
{
var producer = new Producer();
// complex initialization here
return producer;
}
}
}
Note that the term factory isn't really appropriate for your example, I would reserve that term for the case where the importer wants to create instances at will, possibly by providing one or more parameters. That could be done with a method export:
public class ProducerFactory
{
[Export(typeof(Func<Type1,Type2,IProducer>)]
public IProducer CreateProducer(Type1 arg1, Type2 arg2)
{
return new Producer(arg1, arg2);
}
}
On the import side, you would then import a Func<Type1,Type2,IProducer> that you can invoke at will to create new instances.
I have some code that put simply, sets an object to a state of PROCESSING, does some stuff, then sets it to SUCCESS. I want to verify that the PROCESSING save is done with the correct values.
The problem is when the verify() tests are performed, .equals() is called on the object as it is at the end of the test, rather than halfway through.
For example the code:
public void process(Thing thing) {
thing.setValue(17);
thing.setStatus(Status.PROCESSING);
dao.save(thing);
doSomeMajorProcessing(thing);
thing.setStatus(Status.SUCCESS);
dao.save(thing);
}
I want to test:
public void test() {
Thing actual = new Thing();
processor.process(actual);
Thing expected = new Thing();
expected.setValue(17);
expected.setStatus(Status.PROCESSING);
verify(dao).save(expected);
// ....
expected.setStatus(Status.SUCCESS);
verify(dao).save(expected);
}
On the first verify, actual.getStatus() is Status.SUCCESS, as Mockito just keeps a reference to the object and can only test it's value at the end.
I have considered that if a when(...) where involved then .equals() would be called at the correct time and the result would only happen if Thing was what I wanted it to be. However, in this case .save() returns nothing.
How can I verify that the object is put into the correct states?
Ok, I found a solution, but it's pretty horrible. Verify is no good to me because it runs too late, and stubbing is hard because the method returns a void.
But what I can do is stub and throw an exception if anything but the expected is called, while validating that something is called:
public void test() {
Thing actual = new Thing();
Thing expected = new Thing();
expected.setValue(17);
expected.setStatus(Status.PROCESSING);
doThrow(new RuntimeException("save called with wrong object"))
.when(dao).saveOne(not(expected));
processor.process(actual);
verify(dao).saveOne(any(Thing.class));
// ....
expected.setStatus(Status.SUCCESS);
verify(dao).saveTwo(expected);
}
private <T> T not(final T p) {
return argThat(new ArgumentMatcher<T>() {
#Override
public boolean matches(Object arg) {
return !arg.equals(p);
}
});
}
This infers that expected is called. Only drawback is that it'll be difficult to verify the method twice, but luckily in my case both DAO calls are to different methods, so I can verify them separately.
Why not just mock the Thing itself and verify that? eg:
public class ProcessorTest {
#Mock
private Dao mockDao;
#InjectMocks
private Processor processor;
#BeforeMethod
public void beforeMethod() {
initMocks(this);
}
public void test() {
Thing mockThing = Mockito.mock(Thing.class);
processor.process(thing);
verify(mockThing).setStatus(Status.PROCESSING);
verify(mockThing).setValue(17);
verify(mockDao).save(mockThing);
verify(mockThing).setStatus(Status.SUCCESS);
}
If you want to explicitly test the order in which these things happen, use an InOrder object:
public void inOrderTest() {
Thing mockThing = Mockito.mock(Thing.class);
InOrder inOrder = Mockito.inOrder(mockThing, mockDao);
processor.process(mockThing);
inorder.verify(mockThing).setStatus(Status.PROCESSING);
inorder.verify(mockThing).setValue(17);
inorder.verify(mockDao).save(mockThing);
inorder.verify(mockThing).setStatus(Status.SUCCESS);
inorder.verify(mockDao).save(mockThing);
}
Mockito has a problem verifying mutable objects. There is an open issue about this (http://code.google.com/p/mockito/issues/detail?id=126)
Maybe you should switch to EasyMock. They use a record/playback pattern and do the verification at the time of the call in contrary to Mockito, where the verification happens after the call.
This Mockito version of the test has the mentioned problem:
#Test
public void testMockito() {
Processor processor = new Processor();
Dao dao = Mockito.mock(Dao.class);
processor.setDao(dao);
Thing actual = new Thing();
actual.setValue(17);
processor.process(actual);
Thing expected1 = new Thing();
expected1.setValue(17);
expected1.setStatus(Status.PROCESSING);
verify(dao).save(expected1);
Thing expected2 = new Thing();
expected2.setValue(19);
expected2.setStatus(Status.SUCCESS);
verify(dao).save(expected2);
}
This EasyMock version works fine:
#Test
public void testEasymock() {
Processor processor = new Processor();
Dao dao = EasyMock.createStrictMock(Dao.class);
processor.setDao(dao);
Thing expected1 = new Thing();
expected1.setValue(17);
expected1.setStatus(Status.PROCESSING);
dao.save(expected1);
Thing expected2 = new Thing();
expected2.setValue(19);
expected2.setStatus(Status.SUCCESS);
dao.save(expected2);
EasyMock.replay(dao);
Thing actual = new Thing();
actual.setValue(17);
processor.process(actual);
EasyMock.verify(dao);
}
In my example doSomeMajorProcessing sets value to 19.
private void doSomeMajorProcessing(Thing thing) {
thing.setValue(19);
}
After reviewing https://code.google.com/archive/p/mockito/issues/126
I was able to get my version of this working (Java 15, Mockito 3.6.28):
// ========= CODE ==========
public void process(Thing thing) {
thing.setValue(17);
thing.setStatus(Status.PROCESSING);
dao.save(thing);
doSomeMajorProcessing(thing);
thing.setStatus(Status.SUCCESS);
dao.save(thing);
}
// ========= TEST ==========
// ++++++ NOTE - put this at class level
private final Dao dao = mock(Dao.class, withSettings().defaultAnswer(new ClonesArguments()));
public void test() {
Thing actual = new Thing();
processor.process(actual);
ArgumentCaptor<Thing> captor = ArgumentCaptor.for(Thing.class);
verify(dao, times(2)).save(captor.capture());
List<Things> savedCalls = captor.getAllValues();
assertEquals(Status.PROCESSING, savedCalls.get(0).getStatus());
assertEquals(Status.SUCCESS, savedCalls.get(1).getStatus());
}
Using argThat with a hamcrest Matcher should do the trick. The Matcher would match its passed thing if the thing has the PROCESSING status:
public class ProcessingMatcher extends BaseMatcher<Thing> {
#Override
public boolean matches(Object item) {
if (item instanceof Thing) {
return ((Thing) item).getStatus() == Status.PROCESSING;
}
return false;
}
#Override
public void describeTo(Description description) {
description.appendText(" has the PROCESSING status");
}
}
And then in your test, use the following code :
public class MyTest {
public void test() {
//...
mockDao.save(argThat(hasTheProcessingStatus()));
}
static ProcessingMatcher hasTheProcessingStatus() {
return new ProcessingMatcher();
}
}