S
slippymississippi
Another thing I see in your code that sends up red flags is
"synchronized(this)" on your thread class ... the correct usage for
mutex protection is something like a library card system. You have a
central resource (book) that multiple threads (customers) want to use,
so you have a system of tracking when the resource is checked out
(library card). One person takes the book, the librarian takes the
card from the book. The next customer in line has to wait for the
librarian to return the card to the book and call "next!"
(notify/notifyAll) before the customer can begin reading. Because you
want to limit the number of people waiting for books, you assign the
library card to the smallest atomic entity possible (book) rather than
larger objects (shelf, room, floor, library).
So, given my brief experience with Java, I believe you should be using
synchronize on a very small static singleton bean that encapsulates
your data and does very little else ... or simply enforce
synchronization (because you never know how someone else is going to
abuse your classes) by setting the data put/get methods to synchronized
on your bean. And yes, unless the data is remarkably atomic, you have
to protect your getters as well as your setters, because there's
nothing stopping the OS from swapping out a thread in the middle of a
data update.
In general, the more atomic the data being protected by the mutex, and
the smaller the amount of code updating this data, the more efficient
will be your code.
"synchronized(this)" on your thread class ... the correct usage for
mutex protection is something like a library card system. You have a
central resource (book) that multiple threads (customers) want to use,
so you have a system of tracking when the resource is checked out
(library card). One person takes the book, the librarian takes the
card from the book. The next customer in line has to wait for the
librarian to return the card to the book and call "next!"
(notify/notifyAll) before the customer can begin reading. Because you
want to limit the number of people waiting for books, you assign the
library card to the smallest atomic entity possible (book) rather than
larger objects (shelf, room, floor, library).
So, given my brief experience with Java, I believe you should be using
synchronize on a very small static singleton bean that encapsulates
your data and does very little else ... or simply enforce
synchronization (because you never know how someone else is going to
abuse your classes) by setting the data put/get methods to synchronized
on your bean. And yes, unless the data is remarkably atomic, you have
to protect your getters as well as your setters, because there's
nothing stopping the OS from swapping out a thread in the middle of a
data update.
In general, the more atomic the data being protected by the mutex, and
the smaller the amount of code updating this data, the more efficient
will be your code.