Bug 569439 - ContextInjectionFactory.make() and garbage collection
Summary: ContextInjectionFactory.make() and garbage collection
Status: NEW
Alias: None
Product: Platform
Classification: Eclipse Project
Component: Runtime (show other bugs)
Version: 4.17   Edit
Hardware: All All
: P3 normal (vote)
Target Milestone: ---   Edit
Assignee: platform-runtime-inbox CLA
QA Contact:
URL:
Whiteboard:
Keywords:
Depends on:
Blocks: 569038
  Show dependency tree
 
Reported: 2020-12-03 14:05 EST by Rolf Theunissen CLA
Modified: 2020-12-03 14:05 EST (History)
0 users

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Rolf Theunissen CLA 2020-12-03 14:05:34 EST
The testcase below shows unexpected behavior with ContextInjectionFactory. When a class is created with the make method, objects will be re-injected. However, there will only be a weak reference to the created object. Therefore, the created object can be garbage collected at any time. This results in confusion for the users of this injection, see for instance Bug 569038.

Is this intended behavior? And if so, is this behavior well documented?


public class InjectTest {

	static public TestObject testObject;

	static class TestObject {
	}

	static class TestObjectReInject {
		@Inject
		public void doInject(TestObject to) {
			testObject = to;
		}
	}

	@Test
	public void testReInjectWeakRef() {
		IEclipseContext context = EclipseContextFactory.create();

		TestObject to1 = new TestObject();
		TestObject to2 = new TestObject();
		TestObject to3 = new TestObject();

		context.set(TestObject.class, to1);

		TestObjectReInject basicResult1 = ContextInjectionFactory.make(TestObjectReInject.class, context);
		assertNotNull(basicResult1);
		assertEquals(testObject, to1);

		context.set(TestObject.class, to2);
		assertEquals(testObject, to2);

		// Force garbage collection
		basicResult1 = null;
		gc();

		context.set(TestObject.class, to3);
		assertEquals(testObject, to3); // <-- FAILS
	}

	public static void gc() {
		Object obj = new Object();
		WeakReference<Object> ref = new WeakReference<>(obj);
		obj = null;
		while (ref.get() != null) {
			System.gc();
		}
	}
}