• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

DvdFileAccess Constructor not thread-safe

 
Carlo Spelgatti
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

In the SCJD book by Andrew (second edition) on page 139 is the constructor of the DvdFileAccess class. This cunstructor doesen't work correctly if called by two threads indepentently. If both threads come to line 93 and check that the dbPath is still null, they both go into the if, create a new RandomAccessFile with the suppliedDbPath, ... and now we are in trouble. Both threads think, that they work on the specified file, but they will just work on one file, the one whose constructor passed the line 94 at last.

Shouldn't we synchronize this constructor?

Regards

Carlo
 
Ronald Wouters
Ranch Hand
Posts: 190
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Carlo,

I have actually run into a similar problem with my URLyBird assignment.
When multiple threads are creating instances of my Data class (one for each client) then when there was a call to create my DataFileAccess class (similar to DvdFileAccess), I also had the problem that, even though my DataFileAccess class is a static member of my Data class, still multiple instances of DataFileAccess got created causing lots of trouble...
My solution to this problem was not to synchronize the constructor of Data itself. That would not have worked because, as I said my DataFileAccess class is a static member of Data. Instead what I did was to synchronize on the class instance of data inside the Data constructor itself like this


Hope this helps.
Regards, Ronald.
 
Carlo Spelgatti
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ronald

Synchronizing the constructor is not possible.
But sychnchronize on dbPath (static) would be
the solution.

You can also synchronize outside of the class, but
I don't like the idea, that other classes need to
know, that the object instantiation is not thread
safe and have to manage this.

Regards, Carlo
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic