SQLite used through sqlite4java program does not end - sqlite

I have a sqlite4java program to connect and run statements on my SQLite database like this in my main method:
public static void main(String[] args) throws SQLiteException {
getPredictions();
}
private static void getPredictions() throws SQLiteException {
int passValue = 408;
SQLiteConnection db = new SQLiteConnection(new File("D:\\sqlite\\CW.db"));
db.open(true);
SQLiteStatement statement = db.prepare("SELECT * FROM user_based_sim WHERE user1 = ? OR user2 = ?;");
try {
statement.bind(1,passValue);
statement.bind(2,passValue);
while (statement.step()) {
System.out.println(statement.columnInt(0));
}
} finally {
statement.dispose();
}
db.dispose();
}
}
The statement prints the right values etc but the program does not end, eg this remains like this until I shut it down manually:
IntelliJ run/stop buttons
Looks to me the while loop doesnt halt, not sure why. I follow the documentation precisely.

I think there might be something else that's going on there, some other thread gets started and never terminates. Just to make sure, I ran the same code that you posted and it terminated fine. Or, possibly, there's something wrong with the database file and SQLite just keeps scanning it after the first result was printed.
To figure out what's going on, run your program in IDEA, and when it hangs in the end, use the "Dump Threads" action in IDEA (a camera-like icon). If that doesn't answer the question right away, please post the thread dump here.
Hope this helps!
Igor

Related

My Windows application freezes using Background worker threads

I have written an application that uses background workers for long running tasks. At times, after the task is completed, the application will freeze. It doesn't do it right away, it will do it after the application sits idle for a little bit of time.
To try to find out where it is hanging, in my development environment I ran it and waited for it to freeze. I then went to Debug > Break All. It is hanging in the Main() method in Program.cs:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
}
The Application.Run line is highlighted as where the application is hung. When I hover my cursor over the carat in the left border I get a tool tip saying "This is the next statement to execute when this thread returns from the current function."
In looking at this code I realized that it is calling the "main" form of the application, which I named "Main." So my first question is does this matter since the current method is named "Main" also? If so, what are the ramifications of renaming the form, if that is possible?
If that is not an issue, then it would go back to the background worker I would imagine. The application never freezes if those long running tasks are never ran. I know that you should never try to access the UI thread from a background worker thread and I don't think I'm doing that but here is some code that hopefully someone may spot something:
First I start the thread from the UI thread passing in an argument:
bgwInternal.RunWorkerAsync(clients)
In the DoWork method it calculates and creates invoices for the passed in argument (clients). It creates PDF files and saves them to disk. None of that work tries to access the UI. It does use the ProgressChanged event handler to update a progress bar and a label in the UI:
private void bgwInternal_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pgbProgress.Value = e.ProgressPercentage;
lblProgress.Text = e.ProgressPercentage.ToString();
}
And finally the RunWorkerCompleted event handler:
private void bgwInternal_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("Error occurred during invoice creation.\n\r\n\rError Message: " + e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (!e.Cancelled)
{
MessageBox.Show("Invoice Creation Complete", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Invoice Creation Cancelled", "Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
btnCreateInv.Enabled = true;
btnClose.Enabled = true;
btnCancel.Enabled = false;
}
Could it be hanging because I'm accessing UI elements in this event handler?
One final note, I was using Application.DoEvents():
while (bgwInternal.IsBusy)
{
Application.DoEvents();
}
But I commented that out to see if it would make a difference and it did not.
Not having a lot of multithreading experience I chose to use background worker threads because they are simple and straightforward. Other than using Debug > Break All I really don't know how to track down the exact reason this is happening.
Any thoughts / ideas would be greatly appreciated.
Thanks.

Sharing Ofstream pointer and rule of 3

I am trying to fix a memory leak found is this code by val-grind. I did not write it, but I reduced the original code down to using ofstream and not filebuf and ostream.
The problem is I can't figure out how to properly delete the ofstream pointer which is shared and called from a virtual getter method in other code. I think this code violates the rule of 3 but trying different assignment and copy constructors did not work.
Below is an example of the basic code I am trying to fix, when it goes to delete the ofstream pointer is seg faults. Before the segfault I was getting a double delete error.
If anyone can please help, I seem to be stuck here, thanks.
class myLogger
{
public:
myLogger(std::string testName);
void createFileLog();
...
protected:
std::ofstream* my_LogStream;
};
void MyLogger::createFileLog()
{
if(Created == false)
{
m_pLogStream = new std::ofstream(logFileName.c_str(), std::ofstream::out);
Created = true;
}
}
myLogger::~myLogger()
{
if(m_pLogStream)
{
delete m_pLogStream;
m_pLogStream = NULL;
}
}
I found in a higher call it was using a copy and calling the destructor twice.

CannotOpen exception when trying to reopen same database

I'm trying to close a current SQLite connection and reopen a new one.
But sometimes, it's actually the same one (DB name is based on my user ID after login).
This fails with the below exception:
SQLite.SQLiteException occurred
_HResult=-2146233088
_message=Could not open database file: one.sql (CannotOpen)
HResult=-2146233088
Message=Could not open database file: one.sql (CannotOpen)
Source=Cirrious.MvvmCross.Plugins.Sqlite.WindowsPhone
StackTrace:
at SQLite.SQLiteConnection..ctor(String databasePath, Boolean storeDateTimeAsTicks)
InnerException:
To test, I've modified N-10-KittensDb, with the below code:
public DataService(ISQLiteConnectionFactory factory)
{
using (_connection = factory.Create("one.sql"))
{
_connection.CreateTable<Kitten>();
}
using (_connection = factory.Create("one.sql"))
{
_connection.CreateTable<Kitten>();
}
}
Why it would fail on the second using with above exception?
I've already tried calling Close(), Dispose() manually, settting connection var to null and calling GC.Collect, but nothing seems to fix this.
If I close the program and restart new, it works fine.
Looks like the file is in use or similar...
I've debugged until before the SQLlite3 code, and this line in the SQLiteConnection constructor:
var r = SQLite3.Open(DatabasePath, out handle);
is the one returning CannotOpen.
Any idea that could help me pass this, aside from closing the app?
Closing the app could be a possibility, but looks like a to strong solution, as my user is just pressing the "log-out" button.

nhibernate transactions and unit testing

I've got a piece of code that looks like this:
public void Foo(int userId)
{
try {
using (var tran = NHibernateSession.Current.BeginTransaction())
{
var user = _userRepository.Get(userId);
user.Address = "some new fake user address";
_userRepository.Save(user);
Validate();
tran.Commit();
}
}
catch (Exception) {
logger.Error("log error and don't throw")
}
}
private void Validate()
{
throw new Exception();
}
And I'd like to unit test if validations ware made correctly. I use nunit and and SQLLite database for testing. Here is test code:
protected override void When()
{
base.When();
ownerOfFooMethod.Foo(1);
Session.Flush();
Session.Clear();
}
[Test]
public void FooTest()
{
var fakeUser = userRepository.GetUserById(1);
fakeUser.Address.ShouldNotEqual("some new fake user address");
}
My test fails.
While I'm debugging I can see that exception is thrown, Commit has not been called. But my user still has "some new fake user address" in Address property, although I was expecting that it will be rollbacked.
While I'm looking in nhibernate profiler I can see begin transaction statement, but it is not followed neither by commit nor by rollback.
What is more, even if I put there try-catch block and do Rollback explicitly in catch, my test still fails.
I assume, that there is some problem in testing environment, but everything seems fine for me.
Any ideas?
EDIT: I've added important try-catch block (at the beginning I've simplified code too much).
If the exception occurs before NH has flushed the change to the database, and if you then keep using that session without evicting/clearing the object and a flush occurs later for some reason, the change will still be persisted, since the object is still dirty according to NHibernate. When rolling back a transaction you should immediately close the session to avoid this kind of problem.
Another way to put it: A rollback will not rollback in-memory changes you've made to persistent entities.
Also, if the session is a regular session, that call to Save() isn't needed, since the instance is already tracked by NH.

OpenCV and (not) returning IplImages, when is it okay, when not?

is it okay to do something like this, the code snippet is of course not complete, just to show what I mean:
void draw(IplImage* image){
cvLine(image,cvPoint(20,20),cvPoint(100,100),cvScalar(0,0,255),1);}
int main(){
cvNamedWindow("preview",CV_WINDOW_AUTOSIZE);
IplImage* image;
image=cvCreateImage(cvSize(480,360),8,3);
while(true){
draw(image);
cvShowImage("preview",image);
int ops=cvWaitKey(10)
if ops!=-1 break;}
cvReleaseImage(&image);cvDestroyWindow("preview");return 0;
}
or will it cause problems if I don't return the IplImage like this:
IplImage* draw(IplImage* image){
cvLine(image,cvPoint(20,20),cvPoint(100,100),cvScalar(0,0,255),1);return image;}
well, the reason why I'm asking is that sometimes it works if I don't return the IplImage. However it may also happen that I'll receive some sort of NULL pointer error message in other cases. If for example I release the image in the function and then create it anew right after that, still being in that function, a crash may happen.
You don't need to return anything, but you definitely need to check for failures!
The problem is that you are not coding safely. You are never checking for failures when calling OpenCV functions, which may result in draw() receiving a NULL pointer as parameter, and that might cause a crash or some other weird behavior along the way.
The first thing you should do is start coding defensively:
IplImage* image = cvCreateImage(cvSize(480,360),8,3);
if (!image)
{
// print error and quit
}
and it wouldn't hurt to add a safety check inside your function:
void draw(IplImage* image)
{
if (!image)
{
// print error
return;
}
cvLine(image,cvPoint(20,20),cvPoint(100,100),cvScalar(0,0,255),1);
}

Resources