We are starting a new application. We want to use Entity Framework. We are little afraid of deleting sql rows accidentally (especially by set related data accidentally etc.)
I thought to disable every delete, since we just mark every row with "validUntil" column and never delete rows.
I saw that it can done by roles in sql, but I want that all logic and control will be just in code.
Maybe in Entity Framework core there is new feature to enable that? I know that it can still write row sql with EF, but we don't afraid of such case.
I also tried remove setters of entities relationships to be more relax, but it broke the normal functionality of EF, and did not look like a good idea.
I saw in the above link a recommendation to use the Repository Pattern, but here it looks like it is not good practice.
How can I work safely with EF?
thanks!
The role option is one way, but you can also override SaveChanges.
public override int SaveChanges()
{
foreach (DbEntityEntry entity in this.ChangeTracker.Entries)
{
if (entity.State == System.Data.EntityState.Deleted)
return;
}
base.SaveChanges();
}
EDIT
I read on git that for EF Core:
If you want to change the delete behavior for all relationships, then
you can use this code in OnModelCreating(...) to bulk set it for all
relationships in your model.
foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
relationship.DeleteBehavior = DeleteBehavior.Restrict;
}
William's answer is pretty much the way to do it, but you can also do something like this.
Set the Delete to throw an exception, and add a DeleteVirtual method. Primarily this is also update, where you can do the soft delete you want via updating the validUntil field.
T IDbContext.Delete<T>(T entity)
{
throw new NotImplementedException();
}
T IDbContext.DeleteVirtual<T>(T entity)
{
this.Entry(entity).State = EntityState.Modified;
return entity;
}
You can override SaveChanges() method in DbContext class and in there you can get a list of deleted entities and change their Status to Unchanged.
public override int SaveChanges()
{
var DeletedEntities = ChangeTracker.Entries().Where(E => E.State == EntityState.Deleted).ToList();
DeletedEntities.ForEach(E =>
{
E.State = EntityState.Unchanged;
});
return base.SaveChanges();
}
Often, I work on Java EE application. Today I'm facing an issue: serialize Collections in servlet context. In my case, my app contains a Servlet Context Listener and many servlets.
The context listener load a ConcurrentHashMap containing several lists of products at initialisation and a task scheduler to refresh this list.
The servlets are supposed to access the right list, based on user provided parameters.
Here the code of my contextInitialized Listener:
public void contextInitialized(ServletContextEvent event) {
app = event.getServletContext();
myMap = new ConcurrentHashMap<String, Catalog>();
myMap.put("FR", new Catalog());
myMap.put("UK", new Catalog());
app.setAttribute("catalogue", myMap);
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new AutomateRefresh(), 0, 60, TimeUnit.MINUTES);
}
In order to show my problem, i created a servlet that display everything which is a boolean or a ConcurrentHashMap in context
I'm not surprised to find this kind of results:
javax.servlet.context.tempdir is equal to...
Working is equal to... true
org.apache.catalina.resources is equal to...
org.apache.tomcat.InstanceManager is equal to...
org.apache.catalina.jsp_classpath is equal to...
javax.websocket.server.ServerContainer is equal to...
org.apache.jasper.compiler.TldCache is equal to...
catalogue is equal to...
org.apache.tomcat.JarScanner is equal to...
As you can see, my two custom keys (the boolean Working and the ConcurrentHashMap catalogue) exists. But catalogue is empty when not accessed inside the Listener.
I found that:
The serialization form of java.util.HashMap doesn't serialize the buckets themselves, and the hash code is not part of the persisted state.
Source: Serializing and deserializing a map with key as string
For many projects a serializable and thread-safe collection is useful. I am probably not the only one who is looking for that (see the amount of topic about servlet context).
ConcurrentHashMap is thread-safe but I am unable to retrieve my data in other servlet (in the same app). Is there an implementation of Collection which is thread-safe and serializable (due to WebLogic server policy) ? Or am I using it in a wrong way ?
EDIT: Code of "Display context servlet"
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{
System.out.println("List of all values in the context:");
Enumeration<?> e = getServletContext().getAttributeNames();
while (e.hasMoreElements())
{
String name = (String) e.nextElement();
System.out.print("\n" + name + " is equal to... ");
// Get the value of the attribute
Object value = this.getServletContext().getAttribute(name);
if (value instanceof ConcurrentHashMap) {
ConcurrentHashMap<String, Catalog> map = (ConcurrentHashMap<String, Catalog>) value;
Iterator<Entry<String, Catalog>> it = map.entrySet().iterator();
while (it.hasNext()) {
ConcurrentHashMap.Entry<String, Catalog> entry = (ConcurrentHashMap.Entry<String, Catalog>)it.next();
System.out.print("\t" + entry.getKey() + "=" + entry.getValue());
}
} else if (value instanceof Boolean) {
System.out.print((Boolean)value);
}
}
}
EDIT2: Like BalusC suggested the HashMap maybe null (a rookie mistake ?).
Here the task code. The task is in the Listener. The Listener initialize the HashMap with new empty object. The task refresh the objects when webapp starts and then every hour.
public class AutomateRefresh implements Runnable {
public void run() {
System.out.println("Scheduler trigger");
if(app.getAttribute("catalogue") instanceof ConcurrentHashMap){
myMap = (ConcurrentHashMap<String, Catalog>) app.getAttribute("catalogue");
//Autorefresh
Iterator<Entry<String, Catalog>> it = myMap.entrySet().iterator();
while (it.hasNext()) {
ConcurrentHashMap.Entry<String, Catalog> entry = (ConcurrentHashMap.Entry<String, Catalog>)it.next();
((Catalog)entry.getValue()).setValid(false);//Set as not valid anymore for further request
try {
((Catalog)entry.getValue()).refreshdb((String) entry.getKey());//TODO rework to use REST API
} catch (SQLException e) {
e.printStackTrace();
}
it.remove(); // avoids a ConcurrentModificationException
app.setAttribute("catalogue", myMap);
app.setAttribute("Working", true);
System.out.println((String)entry.getKey() + " = " + (Catalog)entry.getValue());
}
}
else{
System.out.println("Catalogue is not an instance of ConcurrentHashMap as expected.");
app.setAttribute("Working", false);
}
}
}
When the task triggered, for each Catalog stored in the Context, the task update the data stored by them. It also display data in console.
Results:
Refresh Catalog for UK with DB
UK = Catalog [list size is : 0 valid=true, lastToken=notoken]
Refresh Catalog for FR with DB
FR = Catalog [list size is : 30 valid=true, lastToken=notoken]
Catalog is a class with an ArrayList, a boolean and a String. Everything seems correct: UK is supposed to be empty but not null and FR is supposed to contains 30 products.
I still can not access this data in other servlets.
I found the origin of the problem, a rookie mistake as expected:
I tried to update this way, assuming it would have updated the object directly in the ConcurrentHashMap
((Catalog)entry.getValue()).refreshdb((String) entry.getKey());
I replace it by:
Catalog myCatalog = (Catalog)entry.getValue();
myCatalog.refreshdb((String) entry.getKey());
myMap.put((String)entry.getKey(), myCatalog);
And it works now.
I still don't know why my objects were accessible from the listener, they are not supposed to work that way. Maybe a strange behavior from my server ? Anyway, this issue is fixed.
Thanks to BalusC for his help.
I've read multiple questions similar to this one but none are exactly my situation.
Using linq-to-sql I insert a new record and submit changes. Then, in the same web request, I pull that same record, and update it, then submit changes. The changes are not saved. The DatabaseContext is the same across both these operations.
Insert:
var transaction = _factory.CreateTransaction(siteId, userId, questionId, type, amount, transactionId, processor);
using (IUnitOfWork unitOfWork = UnitOfWork.Begin())
{
transaction.Amount = amount;
_transactionRepository.Add(transaction);
unitOfWork.Commit();
}
Select and Update:
ITransaction transaction = _transactionRepository.FindById(transactionId);
if (transaction == null) throw new Exception(Constants.ErrorCannotFindTransactionWithId.FormatWith(transactionId));
using (IUnitOfWork unitOfWork = UnitOfWork.Begin())
{
transaction.CrmId = crmId;
transaction.UpdatedAt = SystemTime.Now();
unitOfWork.Commit();
}
Here's the unit of work code:
public virtual void Commit()
{
if (_isDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
_database.SubmitChanges();
}
I even went into the designer.cs file and put a breakpoint on the field that is being set but not updated. I stepped through and it entered and execute the set code, so the Entity should be getting "notified" of the change to this field:
public string CrmId
{
get
{
return this._CrmId;
}
set
{
if ((this._CrmId != value))
{
this.OnCrmIdChanging(value);
this.SendPropertyChanging();
this._CrmId = value;
this.SendPropertyChanged("CrmId");
this.OnCrmIdChanged();
}
}
}
Other useful information:
ObjectTracking is enabled
No errors or exceptions when second SubmitChanges is called (just silently fails update)
SQL profiler shows insert and select but not the subsequent update statement. Linq-To-Sql is not generating the update statement.
There is only one database, one database string, so the update is not going to another database
The table has a primary key.
I don't know what would cause Linq-To-Sql to not issue the update command and not raise some kind of error. Perhaps the problem stems from using the same DataContext instance? I've even refreshed the object from the database using the DataContact.Refresh method before it is pulled for the update, but that didn't help.
I have found what is likely to be the root cause. I am using Unity. The initial insert is being performed in a service class with a PerWebRequest lifetime. The select and update is happening in a class with a Singleton lifetime. So my assumption that the DataContext instances are the same was incorrect.
So, in my class with the Singleton lifetime, I get a fresh instance of the database repository and perform the update and no problem.
Now I still don't know why the original code didn't work and my approach could still be considered more a workaround than a solution, but it did solve my problem and hopefully will be useful to others.
I'm looking to build a library that needs to be very careful about memory management. Basically, I have to create a static factory to "disperse" instances of my tool to requesting objects. (I don't have a choice in this matter, I really do have to use a singleton) We'll call that class FooFactory. FooFactory defines a single method, getFoo(key:String):Foo.
getFoo looks in a private static flash.utils.Dictionary object for the appropriate Foo instance, and either lazy-instantiates it, or simply returns it. In any case, FooFactory MUST keep a reference to each Foo instance created, so all Foo instances can be updated by FooFactory using a method called updateFoos():void.
Here is some pseudo-code of what I'm talking about:
public class FooFactory {
private static const foos:Dictionary = new Dictionary(true); //use weak keys for gc
public static function getFoo(key:String):Foo {
//search for the specified instance in the 'foos' dictionary
if (foos[key] != null && foos[key] != undefined) {
return foos[key];
} else {
//create foo if it doesn't exist.
var foo:Foo = new Foo(key);
foos[key] = foo;
return foo;
}
}
public static function updateFoos():void {
for (var key:String in foos) {
if (foos[key] != null && foos[key] != undefined) {
Foo(foos[key]).dispatchEvent(new Event("update"));
}
}
}
}
The actual function and identity of Foo isn't too important.
What IS important is garbage collection in this situation. I created something similar to the above example in the past and had incredible garbage collection issues. (I did use an array rather than a dictionary, which could be part of the problem.) What would happen is that, in my Flex application, modules would never unload, since instances had a reference to a Foo instance which was referenced by the FooFactory, like so: (again, pseudocode)
<?xml version="1.0"?>
<s:Group>
<fx:Script>
<![CDATA[
private static const foo:Foo = FooFactory.getFoo('myfoo');
]]>
</fx:Script>
</s:Group>
What I want to know are the two following things:
Is the pseudo-code above "garbage-collector safe?" IE: Will my modules unload properly and will instances of the Group subclass above get garbage collected?
Is there a way in Flash Player (even in the debug player if need be) that can assist me in counting references so I can test if things are getting garbage collected or not?
I'm aware of the flash.sampler API, but I am not sure as to how to use it to count references.
I don't think that the pattern you presented should give you problems GC-wise.
private static const foo:Foo = FooFactory.getFoo('myfoo');
Here, your module has a reference to a Foo instance. That means that this Foo instance won't be collectable as long as your module is not collectable. The module has a reference to foo, so here foo is reachable (if the module is reachable). That's not true the other way round. Even if foo lives forever, it doesn't have a reference to the module, so it won't pint it down.
Of course there could be other stuff going on to prevent your module from being collectable, but foo is not the culprit here, unless foo gets a reference to the module somehow. For instance, the module adds a listener to foo, which for this matter, is the same as writing:
foo.addReference(this); // where this is your module
The fact that you declare the instance as const shouldn't change things per se, either. It only means that the reference stored cannot be changed at a later point. However, if you want to null out foo at some later point, you can't because that would be reassigning the reference; and you can't reassigning a const reference (you should get a compiler error). Now, this does tie foo to module. As long as your module is alive it will have a reference to foo, so foo won't be collectable.
Regarding this line:
private static const foos:Dictionary = new Dictionary(true); //use weak keys for gc
It looks like you're trying to build some kind of cache. I'm not sure you want to use weak refs here. (I could be wrong here because I'm making an assumption, and they say assumption is the mother of all... mistakes, but I digress)
In any case, the effect of this is that if a module gets a Foo and at some point the module is successfully unloaded (I mean, cleaned up from memory), that instance of foo could be collected, provided that no one else has a ref to it (that is, the only way to reach it is through the dictionary key, but since the keys are weak referenced, this ref will not count for the purposes of the GC).
Regarding your second question, I'd recommend the FlexBuilder/FlashBuilder profiler, if FB is available to you. It's not the most intuitive tool, granted, but with some practice it could be really useful to track memory problems. Basically, it will let you know how many instances of a given class were created, how many of those are still alive, what objects have references to these instances and where were all these objects allocated (an option not checked by default when you launch the profiler, buy very handy to track a leak).
PS
Regarding your comment:
Perhaps the real issue is the static
const reference bound by the Group
instance? If that's an issue, I could
simply abstract Foo to an interface,
then create something called
FooWeakReference which would use a
weak dictionary to reference the
actual Foo object. Thoughts?
Adding this extra layer of indirection only complicates things and makes your code less obvious for no gain here, I think. It's easier to consider the life-cycle of your module and define clear points of initialization and finalization. When it's finalized, make sure you remove any reference to the module added to the foo instance (i.e. if you have added listeners on foo, remove them, etc), so your module is collectable independently of the life-cycle of foo.
As a general rule, whenever a weak reference seems to solve a bug in your app, it's masking another one or covering up for a poor design; there are exceptions (and compromises that have to be made sometimes), but weak refs are abused gratuitously if you ask me; not everyone will agree, I know.
Also, weak-refs open a whole new kind of bugs: what happens if that instance you created lazily vanishes before you can use it or worse, while you are using it? Event listeners that stop working under not deterministically reproducible circumstances (e.g. you added a listener to an object that is gone), possible null references (e.g. you are trying to add a listener to an object that no longer exists), etc, etc. Don't drink the weak reference kool-aid ;).
Addedum
In conclusion, as one last question,
is it true for me to say that no AS3
solution exists for counting
references? I'm building a complete
unit-testing suite for this library
I'm building, and if I could do
something like Assert.assertEquals(0,
getReferenceCount(foo)), that would be
rad.
Well, yes. You can't get the reference count of a given object from Actionscript. Even if it were possible, I'm not sure that would help, because reference counting is only a part of how GC works. The other one is a mark and sweep algorithm. So, if an object has a zero ref-count is collectable, but it could have, say, 3 references and still be collectable. To really determine whether an object is collectable or not, you should really be able to hook into the GC routine, I guess, and that's not possible from AS.
Also, this code will never work.
Assert.assertEquals(0, getReferenceCount(foo)
Why? Here you are trying to query some API to know whether an object is collectable or not. Since you can't know that, let's assume this tells you whether an object has been collected or not. The problem is, foo at that point is either null or not null. If it's null, it's not a valid reference, so you can't get any useful information out of it, for obvious reasons. If it's not null, it's a valid reference to an object, then you can access it and it's alive; so you already know the answer to the question you're asking.
Now, I think I undestand your goal. You want to be able to tell, programatically, if you certain objects are being leaked. Up to some extent that's possible. It involves using the flash.sampler API, as you mentioned in your original question.
I suggest you check out the Flash Preload Profiler by jpauclair:
I haven't used it, but it looks like it could be just as good as the FB profiler for memory watching.
Since this is Actionscript code (and since it's open source), you could to use it for what you want. I just skimmed through the code, but I've been able to get a very simple-minded proof of concept by monkey-patching the SampleAnalyzer class:
There's a lot of other things going on in this tool, but I just modified the memory analizer to be able to return a list of the alive objects.
So, I wrote a simple class that would run this profiler. The idea is that when you create an object, you can ask this class to watch it. This objects' allocation id will be looked up in the allocated objects table maintained by the memory profiler and a handle to it will be stored locally (only the id). This id handle will also be returned for convenience. So you can store this id handle and at a later point, use it to check whether the object has been collected or not. Also, there's a method that returns a list of all the handles you added and another one that returns a list of the added handles that point to live objects. A handle will allow you to access the original object (if it hasn't been collected yet), its class and also the allocation stack trace. (I'm not storing the object itself or the NewObjectSample object to avoid accidentally pinning it down)
Now, this is important: this queries for alive objects. The fact that an object is alive doesn't mean it's not collectable. So, this alone doens't mean there's a leak. It could be alive at this point but still it doesn't mean there's a leak. So, you should combine this with forcing GC to get more relevant results. Also, this could be of use if you are watching objects that are owned by you and not shared with other code (or other modules).
So, here's the code to the ProfileRunner, with some comments.
import flash.sampler.Sample;
import flash.sampler.NewObjectSample;
import flash.utils.Dictionary;
class ProfilerRunner {
private var _watched:Array;
public function ProfilerRunner() {
_watched = [];
}
public function init():void {
// setup the analyzer. I just copied this almost verbatim
// from SamplerProfiler...
// https://code.google.com/p/flashpreloadprofiler/source/browse/trunk/src/SamplerProfiler.as
SampleAnalyzer.GetInstance().ResetStats();
SampleAnalyzer.GetInstance().ObjectStatsEnabled = true;
SampleAnalyzer.GetInstance().InternalEventStatsEnabled = false;
SampleAnalyzer.GetInstance().StartSampling();
}
public function destroy():void {
_watched = null;
}
private function updateSampling(hook:Function = null):void {
SampleAnalyzer.GetInstance().PauseSampling();
SampleAnalyzer.GetInstance().ProcessSampling();
if(hook is Function) {
var samples:Dictionary = SampleAnalyzer.GetInstance().GetRawSamplesDict();
hook(samples);
}
SampleAnalyzer.GetInstance().ClearSamples();
SampleAnalyzer.GetInstance().ResumeSampling();
}
public function addWatch(object:Object):WatchHandle {
var handle:WatchHandle;
updateSampling(function(samples:Dictionary):void {
for each(var sample:Sample in samples) {
var newSample:NewObjectSample;
if((newSample = sample as NewObjectSample) != null) {
if(newSample.object == object) {
handle = new WatchHandle(newSample);
_watched.push(handle);
}
}
}
});
return handle;
}
public function isActive(handle:WatchHandle):Boolean {
var ret:Boolean;
updateSampling(function(samples:Dictionary):void{
for each(var sample:Sample in samples) {
var newSample:NewObjectSample;
if((newSample = sample as NewObjectSample) != null) {
if(newSample.id == handle.id) {
ret = true;
break;
}
}
}
});
return ret;
}
public function getActiveWatchedObjects():Array {
var list:Array = [];
updateSampling(function(samples:Dictionary):void {
for each(var handle:WatchHandle in _watched) {
if(samples[handle.id]) {
list.push(handle);
}
}
});
return list;
}
public function getWatchedObjects():Array {
var list:Array = [];
for each(var handle:WatchHandle in _watched) {
list.push(handle);
}
return list;
}
}
class WatchHandle {
private var _id:int;
private var _objectProxy:Dictionary;
private var _type:Class;
private var _stack:Array;
public function get id():int {
return _id;
}
public function get object():Object {
for(var k:Object in _objectProxy) {
return k;
}
return null;
}
public function get stack():Array {
return _stack;
}
public function getFormattedStack():String {
return "\t" + _stack.join("\n\t");
}
public function WatchHandle(sample:NewObjectSample) {
_id = sample.id;
_objectProxy = new Dictionary(true);
_objectProxy[sample.object] = true;
_type = sample.type;
_stack = sample.stack;
}
public function toString():String {
return "[WatchHandle id: " + _id + ", type: " + _type + ", object: " + object + "]";
}
}
And here's a simple demo of how you'd use it.
It initializes the runner, allocates 2 Foo objects and then, after 2 seconds, it finalizes itself. Note that in the finalizer, I'm nulling out one of the Foo objects and finalizing the profiler. There I try to force GC, wait for some time (GC is not synchronous) and then check if these objects are alive. The first object should return false, and the second true. So, this is the place were you'd put your assert. Keep in mind that all of this will only work in a debug player.
So, without any further addo, here's the sample code:
package {
import flash.display.Sprite;
import flash.sampler.NewObjectSample;
import flash.sampler.Sample;
import flash.system.System;
import flash.utils.Dictionary;
import flash.utils.setTimeout;
public class test extends Sprite
{
private var x1:Foo;
private var x2:Foo;
private var _profiler:ProfilerRunner;
private var _watch_x1:WatchHandle;
private var _watch_x2:WatchHandle;
public function test()
{
init();
createObjects();
setTimeout(finalize,2000);
}
public function init():void {
initProfiler();
}
public function finalize():void {
x1 = null;
finalizeProfiler();
}
private function initProfiler():void {
_profiler = new ProfilerRunner();
_profiler.init();
}
private function finalizeProfiler():void {
// sometimes, calling System.gc() in one frame doesn't work
// you have to call it repeatedly. This is a kind of lame workaround
// this should probably be hidden in the profiler runner
var count:int = 0;
var id:int = setInterval(function():void {
System.gc();
count++;
if(count >= 3) {
clearInterval(id);
destroyProfiler();
}
},100);
}
private function destroyProfiler():void {
// boolean check through saved handles
trace(_profiler.isActive(_watch_x1));
trace(_profiler.isActive(_watch_x2));
// print all objects being watched
trace(_profiler.getWatchedObjects());
// get a list of the active objects and print them, plus the alloc stack trace
var activeObjs:Array = _profiler.getActiveWatchedObjects();
for each(var handle:WatchHandle in activeObjs) {
trace(handle);
trace(handle.getFormattedStack());
}
_profiler.destroy();
}
private function createObjects():void {
x1 = new Foo();
x2 = new Foo();
// add them for watch. Also, let's keep a "handle" to
// them so we can query the profiler to know if the object
// is alive or not at any given time
_watch_x1 = _profiler.addWatch(x1);
_watch_x2 = _profiler.addWatch(x2);
}
}
}
import flash.display.Sprite;
class Foo {
public var someProp:Sprite;
}
Alternatively, a more light-weight approach for tracking alive objects is storing them in a weak-referenced dictionary, forcing GC and then checking how many objects are stil alive. Check out this answer to see how this could be implemented. The main difference is that this gives you less control, but maybe it's good enough for your purposes. Anyway, I felt like giving the other idea a shot, so I wrote this object watcher and kind of like the idea.
Since you essentially want weak references, perhaps the best solution would involve one of the weak references available in AS3.
For example, have your method store Dictionaries rather than the actual objects. Something like this:
private var allFoos:Dictionary;
public function getFoo(key:String):Foo {
var f:Foo = _getFoo(key);
if (f == null) {
f = _createFoo(key);
}
return f;
}
private function _createFoo(key:String):Foo {
var f:Foo = new Foo();
var d:Dictionary = new Dictionary(/* use weak keys */ true);
d[f] = key;
allFoos[key] = d;
}
With some intense thinking over the weekend, I believe I figured out what the problem is.
Essentially, we have this scenario:
.--------------.
| APP-DOMAIN 1 |
| [FooFactory] |
'--------------'
|
| < [object Foo]
|
.--------------.
| APP-DOMAIN 2 |
| [MyModule] |
'--------------'
APP-DOMAIN 1 always stays in memory, since it's loaded in the highest app-domain possible: the original compiled code of a SWF. APP-DOMAIN 2 is loaded into and out of memory dynamically and must be able to completely sever itself from APP-DOMAIN 1. According to the genius answer above by Juan Pablo Califano, APP-DOMAIN 2 having a reference to [object Foo] doesn't necessarily tie APP-DOMAIN 2 into memory, though it could become tied into memory by [MyModule] adding an event listener to [object Foo], right?
Okay, so, with this in mind, an overkill solution would be to return a weak-reference-implementation of Foo from the getFoo method, since that's where things need to "break off" in case of "emergency." (Things need to be weak from this perspective so that APP-DOMAIN 1 can be garbage collected completely as it is unloaded.) Again, this is an overkill answer.
However, I do not need to keep a weak-ref to Foo in FooFactory, since FooFactory needs to have a surefire way of getting a hold of each created Foo object. In short, Juan Pablo Califano has the theory completely right, it just needs to be tested in the real world in order to prove everything definitively :)
All of this aside, I believe I have uncovered the real issue behind the scenes that caused a similar library I wrote in the past to never GC. The problem was not in the actual library I wrote, but it seems that it was in a reflection library I was using. The reflection library would "cache" every Class object I threw at it, since my original FooFactory.getFoo method took a Class parameter, rather than a String. Since the library seemed to be hard-referencing every Class object passed into memory, I'm pretty sure that was the memory leak.
In conclusion, as one last question, is it true for me to say that no AS3 solution exists for counting references? I'm building a complete unit-testing suite for this library I'm building, and if I could do something like Assert.assertEquals(0, getReferenceCount(foo)), that would be rad.
I'm trying to follow the examples provided in this post, to create a dynamic list constraint in Alfresco 3.3.
So, I've created my own class extending ListOfValuesConstraint:
public class MyConstraint extends ListOfValuesConstraint {
private static ServiceRegistry registry;
#Override
public void initialize() {
loadData();
}
#Override
public List getAllowedValues() {
//loadData();
return super.getAllowedValues();
}
#Override
public void setAllowedValues(List allowedValues) {
}
protected void loadData() {
List<String> values = new LinkedList<String>();
String query = "+TYPE:\"cm:category\" +#cm\\:description:\"" + tipo + "\"";
StoreRef storeRef = new StoreRef("workspace://SpacesStore");
ResultSet resultSet = registry.getSearchService().query(storeRef, SearchService.LANGUAGE_LUCENE, query);
// ... values.add(data obtained using searchService and nodeService) ...
if (values.isEmpty()) {
values.add("-");
}
super.setAllowedValues(values);
}
}
ServiceRegistry reference is injected by Spring, and it's working fine. If I only call loadData() from initialize(), it executes the Lucene query, gets the data, and the dropdown displays it correctly. Only that it's not dynamic: data doesn't get refreshed unless I restart the Alfresco server.
getAllowedValues() is called each time the UI has to display a property having this constraint. The idea on the referred post is to call loadData() from getAllowedValues() too, so the values will be actually dynamic. But when I do this, I don't get any data. The Lucene query is the same, but returns 0 results, so my dropdown only displays -.
BTW, the query I'm doing is: +TYPE:"cm:category" +#cm\:description:"something here", and it's the same on each case. It works from initialize, but doesn't from getAllowedValues.
Any ideas on why is this happening, or how can I solve it?
Thanks
Edit: we upgraded to Alfresco 3.3.0g Community yesterday, but we're still having the same issues.
This dynamic-list-of-values-constraint is a bad idea and I tell you why:
The Alfresco repository should be in a valid state all the time. Your (dynamic) list of constraints will change (that's why you want it to be dynamic). Adding items would not be a problem, but editing and removing items are. If you would remove an item from your option-list, the nodes in the repository with this property value will be invalid.
You will not be able to fix this easily. The standard UI will fail on invalid-state-nodes. Simply editing this value and setting it to something valid will not work. You have been warned.
Because the default UI widget for a ListConstraint is a dropdown, not every dropdown should be a ListConstraint. ListConstraints are designed for something like a Status property: { Draft, Waiting Approval, Approved }. Not for a list of customer-names.
I have seen this same topic come up again and again over the last few years. What you actually want is let the user choose a value from a dynamic list of options (combo box). This is a UI problem, not a dictionary-model-issue. You should setup something like this with the web-config-context.xml (Alfresco web UI) or in Alfresco Share. The last one is more flexible and I would recommend taking that path.