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, 2229👍, 0💬
Popular Posts:
How To Wirte a Simple JUnit Test Class? This is a common test in a job interview. You should be able...
What is DAR (Decision Analysis and Resolution) ? Decision Analysis and Resolution is to analyze poss...
Can Java object be locked down for exclusive use by a given thread? Yes. You can lock an object by p...
How To Merge Cells in a Column? - XHTML 1.0 Tutorials - Understanding Tables and Table Cells If you ...
Can Multiple Cursors Being Opened at the Same Time? - Oracle DBA FAQ - Working with Cursors in PL/SQ...