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, 2154👍, 0💬
Popular Posts:
How is the MVC design pattern used in Struts framework? In the MVS design pattern, there 3 component...
What is cross page posting? By default, button controls in ASP.NET pages post back to the same page ...
What is XSLT? XSLT is a rule based language used to transform XML documents in to other file formats...
What Is a CAPTION Tag/Element? - XHTML 1.0 Tutorials - Understanding Tables and Table Cells A "capti...
What is the quickest sorting method to use? The answer depends on what you mean by quickest. For mos...