Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
This class (IncrementImpl) will be used by various threads concurrently; can you see the inherent flaw(s)? How would you improve
This class (IncrementImpl) will be used by various threads concurrently; can you see the inherent flaw(s)? How would you improve it?
✍: Guest
public class IncrementImpl { private static int counter = 0; public synchronized void increment() { counter++; } public int getCounter() { return counter; } }
The counter is static variable which is shared by multiple instances of this class. The increment() method is synchronized, but the getCounter() should be synchronized too. Otherwise the Java run-time system will not guarantee the data integrity and the race conditions will occur. The famous producer/consumer example listed at Sun's thread tutorial site will tell more.
one of solutions
public class IncrementImpl { private static int counter = 0; public synchronized void increment() { counter++; } public synchronized int getCounter() { return counter; } }
2012-08-28, 2264👍, 0💬
Popular Posts:
What does a special set of tags <?= and ?> do in a PHP script page? <?= express...
If cookies are not enabled at browser end does form Authentication work? No, it does not work.
How To Change the Password of Another User Account? - MySQL FAQs - Managing User Accounts and Access...
How To Create an Add-to-NewsGator Button on Your Website? - RSS FAQs - Adding Your Feeds to RSS News...
Do events have return type ? No, events do not have return type.