Where can I find documentation for NHibernate ISession.Persist()? - nhibernate

NHibernate's ISession exposes a method Persist() with two overloads. I cannot find documentation on this method anywhere. It's not even mentioned in the NHibernate reference material on http://nhibernate.info/doc/nh/en/index.html.
Is this method deprecated, or will it be? When is it supposed to be used? How does it compare to SaveOrUpdate()?
Any pointers would be much appreciated.

The last comment on this thread http://opensource.atlassian.com/projects/hibernate/browse/HHH-1273 specifies it very well:
persist() is well defined. It makes a
transient instance persistent.
However, it doesn't guarantee that the
identifier value will be assigned to
the persistent instance immediately,
the assignment might happen at flush
time. The spec doesn't say that, which
is the problem I have with persist().
persist() also guarantees that it will
not execute an INSERT statement if it
is called outside of transaction
boundaries. This is useful in
long-running conversations with an
extended Session/persistence context.
A method like persist() is required.
save() does not guarantee the same, it
returns an identifier, and if an
INSERT has to be executed to get the
identifier (e.g. "identity" generator,
not "sequence"), this INSERT happens
immediately, no matter if you are
inside or outside of a transaction.
This is not good in a long-running
conversation with an extended
Session/persistence context.
Also it seems from what I could gather from other sources that an entity having cascade="persist" will cascade at the time of the call, not on flush. That might very useful too.

Related

Stamping / Tagging / Branding Object Instances

I have a routine which accepts an object and does some processing on it. The objects may or may-not be mutable.
void CommandProcessor(ICommand command) {
// do a lot of things
}
There is a probability that the same command instance loops back in the processor. Things turn nasty when that happens. I want to detect these return visitors and prevent them from being processed. question is how can I do that transparently i.e. without disturbing the object themselves.
here is what i tried
Added a property Boolean Visited {get, set} on the ICommand.
I dont like this because the logic of one module shows up in other. The ShutdownCommand is concerned with shutting down, not with the bookkeeping. Also an EatIceCreamCommand may always return False in a hope to get more. Some non-mutable objects have outright problems with a setter.
privately maintain a lookup table of all processed instances. when an object comes first check against the list.
I dont like this either. (1) performance. the lookup table grows large. we need to do liner search to match instances. (2) cant rely on hashcode. the object may forge a different hashcode from time to time. (3) keeping the objects in a list prevents them from being garbage collected.
I need a way to put some invisible marker on the instance (of ICommand) which only my code can see. currently i dont discriminate between the invocations. just pray the same instances dont come back. does anyone have a better idea to implement this functionality..?
Assuming you can't stop this from happening just logically (try to cut out the loop) I would go for a HashSet of commands that you've already seen.
Even if the objects are violating the contracts of HashCode and Equals (which I would view as a problem to start with) you can create your own IEqualityComparer<ICommand> which uses System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode to call Object.GetHashCode non-virtually. The Equals method would just test for reference identity. So your pool would contain distinct instances without caring whether or how the commands override Equals and GetHashCode.
That just leaves the problem of accumulating garbage. Assuming you don't have the option of purging the pool periodically, you could use WeakReference<T> (or the non-generic WeakReference class for .NET 4) to avoid retaining objects. You would then find all "dead" weak references every so often to prevent even accumulating those. (Your comparer would actually be an IEqualityComparer<WeakReference<T>> in this case, comparing the targets of the weak references for identity.)
It's not particularly elegant, but I'd argue that's inherent in the design - you need processing a command to change state somewhere, and an immutable object can't change state by definition, so you need the state outside the command. A hash set seems a fairly reasonable approach for that, and hopefully I've made it clear how you can avoid all three of the problems you mentioned.
EDIT: One thing I hadn't considered is that using WeakReference<T> makes it hard to remove entries - when the original value is garbage collected, you're not going to be able to find its hash code any more. You may well need to just create a new HashSet with the still-alive entries. Or use your own LRU cache, as mentioned in comments.

Is Android's SQLiteStatement (prepared statement) thread-safe? I.e. is "bind*, bind*... execute" atomic?

I'm wondering whether prepared statements in Android (instances of SQLiteStatement) are thread-safe. In particular I'm asking with regard to the following scenario:
In a ContentProvider you create a pre-compiled insert statement during onCreate. Then, in the overriden insert method you make use of this statement by binding a set of parameters to it and calling executeInsert on it.
We know that a ContentProvider has to be written in a thread-safe manner. If SQLiteStatement does not bind parameters per thread, a concurrent call to the provider's insert method would alter the statement's bindings and result in unpredictable behavior.
Android's own Contacts provider uses prepared statements in this way (http://bit.ly/bDuKAT), so I tend to believe that they are in fact thread-safe. Looking at the source code of SQLiteStatement I don't see how though (http://bit.ly/9M1Swv).
So, is SQLiteStatement (or SQLiteProgram that is) thread-safe with respect to parameter binding or not?
It is explicitly stated in the SQLiteStatement documentation that
SQLiteStatement is not internally synchronized
Thus, the class is not thread-safe and cannot be used by multiple threads concurrently without unexpected results.
If it's two separate methods, then it can't possibly be thread-safe:
mStatusUpdateDelete.bindLong(1, dataId);
mStatusUpdateDelete.execute();
The first thread could call bindLong with 1, then the second thread with 2, and then both threads could call execute. So even if bindLong and execute internally are thread safe, it wouldn't help.

What Getters and Setters should and shouldn't do [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Convention question: When do you use a Getter/Setter function rather than using a Property
I've run into a lot of differing opinions on Getters and Setters lately, so I figured I should make it into it's own question.
A previous question of mine received an immediate comment (later deleted) that stated setters shouldn't have any side effects, and a SetProperty method would be a better choice.
Indeed, this seems to be Microsoft's opinion as well. However, their properties often raise events, such as Resized when a form's Width or Height property is set. OwenP also states "you shouldn't let a property throw exceptions, properties shouldn't have side effects, order shouldn't matter, and properties should return relatively quickly."
Yet Michael Stum states that exceptions should be thrown while validating data within a setter. If your setter doesn't throw an exception, how could you effectively validate data, as so many of the answers to this question suggest?
What about when you need to raise an event, like nearly all of Microsoft's Control's do? Aren't you then at the mercy of whomever subscribed to your event? If their handler performs a massive amount of information, or throws an error itself, what happens to your setter?
Finally, what about lazy loading within the getter? This too could violate the previous guidelines.
What is acceptable to place in a getter or setter, and what should be kept in only accessor methods?
Edit:
From another article in the MSDN:
The get and set methods are generally no different from other methods. They can perform any program logic, throw exceptions, be overridden, and be declared with any modifiers allowed by the programming language. Note, however, that properties can also be static. If a property is static, there are limitations on what the get and set methods can do. See your programming language reference for details.
My view:
If a setter or getter is expected to be expensive, don't make it a property, make it a method.
If setting a property triggers events due to changes, this is fine. How else would you allow listeners to be notified of changes? However, you may want to offer a BeginInit/EndInit pair to suppress events until all changes are made. Normally, it is the responsibility of the event handler to return promptly, but if you really can't trust it to do so, then you may wish to signal the event in another thread.
If setting a property throws exceptions on invalid values, it's also fine. This is a reasonable way to signal the problem when the value is completely wrong. In other cases, you set a bunch of properties and then call a method that uses them to do something, such as make a connection. This would allow holding off validation and error-handling until the properties are used, so the properties would not need to throw anything.
Accessing a property may have side-effects so long as they aren't unexpected and don't matter. This means a JIT instantiation in a getter is fine. Likewise, setting a dirty flag for the instance whenever a change is made is just fine, as it setting a related property, such as a different format for the same value.
If it does something as opposed to just accessing a value, it should be a method. Method are verbs, so creating a connection would be done by the OpenConnection() method, not a Connection property. A Connection property would be used to retrieve the connection in use, or to bind the instance to another connection.
edit - added 5, changed 2 and 3
I agree with the idea that getters/settings shouldn't have side effects, but I would say that they shouldn't have non-obvious side effects.
As far as throwing exceptions, if you are setting a property to an invalid value (in a very basic sense), then validation exceptions are fine. However, if the setter is running whole series of complicated business rule validation, or trying to go off and update other objects, or any other thing that may cause an exception, then that is bad. But this problem is not really an issue with the exception itself, but rather that the setter is going off and secretly performing a lot of functionlity that the caller would not (or should not) expect.
The same with events. If a setter is throwing an event saying that "this property changed", then it's OK, because that's an obvious side effect. But if it's firing off some other custom event so cause some hidden chuck of code to execute in another part of a system, it's bad.
This is the same reason that I avoid lazy-loading in getters. Indeed, they can make things easier a lot of the time, but they can make things a more confusing some of the time, because there always ends up being convoluted logic around exactly when you want the child objects loaded. It's usually just one more line of code to explicitly load the child objects when you are populating the parent object, and it can avoid a lot of confusion about the object state. But this aspect can get very subjective, and a lot of it depends on the situation.
I've always found the conservative approach to be best, when working in C# anyway. Because properties are syntactically the same as fields, they should work like fields: no exceptions, no validation, no funny business. (Indeed, most of my properties start out as simple fields, and don't become properties until absolutely necessary.) The idea is that if you see something that looks like it's getting or setting a field set, then it IS something like getting or setting a field, in terms of functionality (there is no exception thrown), overall efficiency (setting variables doesn't trigger a cascade of delegate calls, for example) and effect on program's state (setting a variable sets that variable, and doesn't call lots of delegates that could do just about anything).
Sensible things for a property set to do include setting a flag to indicate that there's been a change:
set {
if(this.value!=value) {
this.changed=true;
this.value=value;
}
}
Perhaps actually set a value on another object, e.g.:
set { this.otherObject.value=value; }
Maybe disentangle the input a bit, to simplify the class's internal code:
set {
this.isValid=(value&Flags.IsValid)!=0;
this.setting=value&Flags.SettingMask;
}
(Of course, in these latter two cases, the get function might well do the opposite.)
If anything more complicated needs to happen, in particular calling delegates, or performing validation, or throwing exceptions, then my view is that a function is better. (Quite often, my fields turn into properties with get and set, and then end up as a get property and a set function.) Similarly for the getters; if you're returning a reference to something, it's no problem, but if you're creating a whole new large object and filling it in each time the property is read -- not so hot.

Object-oriented programming & transactions

A little intro:
Class contains fields and methods (let me skip properties this time).
Fields represent a state of the class.
Methods describe behavior of the class.
In a well-designed class, a method won't change the class's state if it throws an exception, right? (In other words, whatever happens, class's state shouldn't be corrupted)
Question:
Is there a framework, a design pattern, best practice or a programming language to call a sequence of methods in a transactional style, so that either class's state don't get changed (in case of exception), or everything succeeds?
E.g.:
// the class foo is now in the state S1
foo.MoveToState2();
// it is now (supposed to be) in the state S2
foo.MoveToFinalState();
// it is now (supposed to be) in the state, namely, S3
Surely, an exception might occur both in MoveToState2() and MoveToFinalState(). But from this block of code I want the class foo to be either in the state S1 or S3.
This is a simple scenario with a single class involved, no if's, no while's, no side effects, but I hope the idea is clear.
Take a look at the Memento pattern
The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).
Not the most efficient method, but you could have an object that represents your transactional data. When you start a transaction, make a copy of the data and perform all operations on that. When the transaction ends successfully, move the copy to your real data - this can be done using pointers, so need not be too inefficient.
Functional programming is a paradigm that seems to fit well to transactional computations. Since no side-effects are allowed without explicit declaration, you have full control of all data flow.
Therefore software transactional memory can be expressed easily in functional terms - See STM for F#
The key idea is the concept of monads. A monad can be used to model an arbitrary computation through two primitives: Return to return a value and Bind to sequence two computations. Using these two, you can model a transactional monad that controls and saves all state in form of continuations.
One could try to model these in an object-oriented way through a State+Memento pattern, but generally, transactions in imperative languages (like the common OO-ones) are much more difficult to implement since you can perform arbitrary side-effects. But of course you can think of an object defining a transaction scope, that saves, validates and restores data as needed, given they expose a suitable interface for this (the patterns I mentioned above).
The simplest and most reliable "pattern" to use here is an immutable data structure.
Instead of writing:
foo.MoveToState2();
foo.MoveToFinalState();
You write:
MyFoo foo2 = foo.MoveToState2();
MyFoo finalFoo = foo2.MoveToFinalState();
And implement the methods accordingly - that is, MoveToState2 does not actually change anything about MyFoo, it creates a new MyFoo that is in state 2. Similarly with the final state.
This is how the string classes in most OO languages work. Many OO languages are also starting to implement (or have already implemented) immutable collections. Once you have the building blocks, it's fairly straightforward to create an entire immutable "entity".
This would be pretty ugly to implement everywhere, but just saving the state locally, then restoring it in the case of an exception would work in simple scenarios. You'd have to catch and rethrow the exception, which may lose some context in some languages. It might be better to wrap it if possible to retain the context.
try {
save state in local variables
move to new state
} catch (innerException) {
restore state from local variables
throw new exception( innerException )
}
When using object copy approach, you have to watch out that the statements to be rolled-back are only affecting the object's or data itself (and aggregates).
But things are getting really difficult if the side-effects of the statements are "more external". For example I/O operations, network calls. You always have to analyze the overall state-changes of your statements.
It gets also really tricky if you touch static data (or evil mutable singletons). Reverting this data isolated is difficult, because other threads could have modified them in between (you could face lost updates).
Reverting/rollback to the past is often not so trivial ;)
I would also consider the saga pattern, you could pass a copy of the objects current state into MoveToState2 and if it throws an exception you could catch that internally and use the copy of the original state to rollback. You would have to do the same with MoveToState3 too. If however the server crashed during a rollback you might still get corrupted state, that's why databases are so good.
Transactional memory fits here the best.
An option could be a transactional storage. Sample implementation you can find here:
http://www.codeproject.com/KB/dotnet/Transactional_Repository.aspx
Memento pattern
Also let me describe a possible pattern on how to implement such behavior:
Define a base class TransactionalEntity. This class contains dictionary of properties.
All your transactional classes inherit from the TransactionalEntity and should operate over some sort of Dependency Properties/Fields, i.e. properties(getters/setters) which store it's values not in local class fields, but in dictionary, which is stored in the base class.
Then you define TransactionContext class. TransactionContext class internally contains a set of dictionaries (one dictionary for each entity that participates in the transaction) and when a transactional entity participates in transaction, it writes all data to the dictionary in the transaction context. Then all you need is basically four methods:
TransactionContext.StartTransaction();
TransactionalEntity.JoinTransaction(TransactionContext context); //if your language/framework supports Thread Static fields, then you do not need this method
TransactionContext.CommitTransaction();
TransactionContext.RollbackTransaction();
To sum up, you need to store state in base class TransactionalEntity and during transaction TransactionalEntity will cooperate with TransactionContext.
I hope, I've explained it well enough.
I think a Command Pattern could be well suited to this problem.
Linky.
I was astonished that no one suggested explicitly the simplest pattern to use .. the State Pattern
In this way you can also eliminate that 'finalState' method and just use 'handle()'.
How do you know which final state is?
The memento pattern is best used with the Command pattern, and usually applies to GUI operations to implement the undo/redo feature.
Fields represent a state of the class
Fields represents the state of the instanced object. You use many times wrong definitions of the OOP terms. Review and correct.

what happens if more than one thread tries to access singleton object

Not during instantiation, but once instantiation of singleton object is done, what will happen if two or more threads are trying to access the same singleton object? Especially in the case where the singleton object takes lot of time to process the request (say 1 min)... In this case, if for ex., 5 threads try to access the same singleton object, what will the result be?
Additional question: normally when should we go for the singleton pattern and when should we avoid it?
Unless synchronization (locking) is being performed within the Singleton, the answer is this: it's a free-for-all.
Though the Singleton ensures that only one instance of an object is used when requested, the pattern itself doesn't inherently provide any form of thread safety. This is left up to the implementer.
In the specific case you cited (with a long running method), it would be critical to synchronize access to any method that uses class or object-level variables. Failure to do so would, in all likelihood, lead to race conditions.
Good luck!
The general rule of thumb i use for Singletons is that it should not affect the running code, and have no side-effects. Essentially for me, in my projects this translates into some kind of logging functionality, or static value lookup (ie. loading some common data from a database once and storing it for reference so it doesn't have to be read in everytime its needed).
A singleton is no different than any other object other than there is only one instance. What happens when you try to access it will largely depend on what the accessing threads are attempting (ie read vs write) and what kind of data your singleton is holding.
The answer to your question as it is, is "it really depends". What kind of singleton? i.e. what does it do, and how does it do it? And in what language?
The reality is that the singleton patter)n only dictates and enforces that you can only have one instance of a certain object. In of itself it does not say anything about multiple threads accessing that object.
So, if coded right (with thread synchronization implemented correctly) there is no reason why it shouldn't behave correctly - even if the requests to the object take a really long time to process!
Then you need thread safe implementation of singleton pattern.
Find this article useful for the same which describes most of the multi-threading scenario of singleton pattern.
HTH!