没有合适的资源?快使用搜索试试~ 我知道了~
首页JVM多线程编程指南:实战解析与最佳实践
JVM多线程编程指南:实战解析与最佳实践
5星 · 超过95%的资源 需积分: 10 2 下载量 177 浏览量
更新于2024-07-29
收藏 3.28MB PDF 举报
"《编程并发在JVM上》是一本备受赞誉的IT专业书籍,作者Venkat凭借其深厚的专业素养,引领读者深入探讨了现代JVM开发者在多线程编程中面临的众多设计和实现决策。该书以易于理解的方式撰写,并辅以丰富的实例,这些实例涵盖了当前开源工具和多种JVM编程语言的实践应用,使得这个复杂的话题变得易于掌握。 Albert Scherer,作为Follett Higher Education Group, Inc.的电子商务技术经理,高度评价这本书是JVM平台选择者的必读书籍。他强烈建议购买并推荐给团队成员,因为它能帮助解决并发问题,找到有效的解决方案。 Raju Gandhi,作为Integrallis Software, LLC的高级顾问,认为这本书对一个至关重要的主题进行了详尽的探讨。它不仅关注新兴并发模型和语言的兴起,还为开发者提供了如何组织应用结构、充分利用现有库的实用指导。 Chris Richardson,知名的《POJOs in Action》作者和CloudFoundry.com的创始人,认可了这本书对于JVM领域的新鲜兴趣和应用的结合。他认为Venkat的书为开发者提供了一个全面的框架,使他们能够有效地利用新语言和技术来构建并发应用,最大化性能潜力。 《编程并发在JVM上》是一本实用的指南,无论是初学者还是经验丰富的开发人员,都能从中受益匪浅。它不仅介绍了理论概念,而且提供了实际操作的实战技巧,帮助开发者解决在JVM平台上实现并发时遇到的各种挑战。无论你是寻求深入理解,还是寻找解决问题的方法,这本书都是不可或缺的参考资料。"
资源详情
资源推荐
In the listing of code examples, I haven’t shown the import statements (and
the package statements) because these often become lengthy. When trying
the code examples, if you’re not sure which package a class belongs to, don’t
worry, I’ve included the full listing on the code website. Go ahead and
download the entire source code for this book from its website (
http://pragprog.
com/titles/vspcon
).
Acknowledgments
Several people concurrently helped me to write this book. If not for the
generosity and inspiration from some of the great minds I’ve come to know
and respect over the years, this book would have remained a great idea in
my mind.
I first thank the reviewers who braved to read the draft of this book and
who offered valuable feedback—this is a better book because of them.
However, any errors you find in this book are entirely a reflection of my de-
ficiencies.
I benefited a great deal from the reviews and shrewd remarks of Brian Goetz
(@B ri a nG oet z) , A le x Mi ll er (@p ure da n ge r), a nd Jo n as Bo n ér ( @jb on e r) . A lm ost
every page in the book was improved by the thorough review and eagle eyes
of Al Scherer (@al_scherer) and Scott Leberknight (@sleberknight). Thank
you very much, gentlemen.
Special thanks go to Raju Gandhi (@looselytyped), Ramamurthy Gopalakr-
ishnan, Paul King (@paulk_asert), Kurt Landrus (@koctya), Ted Neward
(@tedneward), Chris Richardson (@crichardson), Andreas Rueger, Nathaniel
Schutta (@ntschutta), Ken Sipe (@kensipe), and Matt Stine (@mstine) for
devoting your valuable time to correct me and encourage me at the same
time. Thanks to Stuart Halloway (@stuarthalloway) for his cautionary review.
I’ve improved this book, where possible, based on his comments.
The privilege to speak on this topic at various NFJS conferences helped
shape the content of this book. I thank the NFJS (@nofluff) director Jay
Zimmerman for that opportunity and my friends on the conference circuit
both among speakers and attendees for their conversations and discussions.
I thank the developers who took the time to read the book in the beta form
and offer their feedback on the book’s forum. Thanks in particular to Dave
Briccetti (@dcbriccetti), Frederik De Bleser (@enigmeta), Andrei Dolganov,
Rabea Gransberger, Alex Gout, Simon Sparks, Brian Tarbox, Michael Uren,
Dale Visser, and Tasos Zervos. I greatly benefited from the insightful com-
ments, corrections, and observations of Rabea Gransberger.
xvi • Preface
report erratum • discuss
Thanks to the creators and committers of the wonderful languages and li-
braries that I rely upon in this book and to program concurrent applications
on the JVM.
One of the perks of writing this book was getting to know Steve Peter, who
endured the first draft of this book as the initial development editor. His
sense of humor and attention to detail greatly helped during the making of
this book. Thank you, Steve. It was my privilege to have Brian P. Hogan
(@bphogan) as the editor for this book. He came up to speed quickly, made
observations that encouraged me, and, at the same time, provided construc-
tive comments and suggestions in areas that required improvements. Thank
you, Brian.
I thank the entire Pragmatic Bookshelf team for their efforts and encourage-
ment along the way. Thanks to Kim Wimpsett, Susannah Pfalzer (@spfalzer),
Andy Hunt (@pragmaticandy), and Dave Thomas (@pragdave) for their help,
guidance, and making this so much fun.
None of this would have been possible without the support of my wife—thank
you, Kavitha, for your incredible patience and sacrifice. I got quite a bit of
encouragement from my sons, Karthik and Krupa; thank you, guys, for being
inquisitive and frequently asking whether I’m done with the book. Now I
can say yes, and it’s where it belongs—in the hands of programmers who’ll
put it to good use.
report erratum • discuss
• xvii
CHAPTER 1
The Power and Perils of Concurrency
You’ve promised the boss that you’ll turn the new powerful multicore pro-
cessor into a blazingly fast workhorse for your application. You’d love to
ex pl o it the po w e r on ha n d a n d be at yo ur com p e t it io n w i th a fas t e r , re s p o ns iv e
application that provides great user experience. Those gleeful thoughts are
interrupted by your colleague’s cry for help—he’s run into yet another syn-
chronization issue.
Most programmers have a love-hate relationship with concurrency.
Programming concurrency is hard, yet the benefits it provides make all the
troubles worthwhile. The processing power we have at our disposal, at such
an affordable cost, is something that our parents could only dream of. We
can exploit the ability to run multiple concurrent tasks to create stellar ap-
plications. We have the ability to write applications that can provide a great
user experience by staying a few steps ahead of the user. Features that
would’ve made apps sluggish a decade ago are quite practical today. To re-
alize this, however, we have to program concurrency.
In this chapter, we’ll quickly review the reasons to exploit concurrency and
discuss the perils that this path is mired in. At the end of this chapter, we’ll
be prepared to explore the exciting options for concurrency presented in
this book.
1.1 Threads: The Flow of Execution
A thread, as we know, is a flow of execution in a process. When we run a
program, there is at least one thread of execution for its process. We can
create threads to start additional flows of execution in order to perform ad-
ditional tasks concurrently. The libraries or framework we use may also
start additional threads behind the scenes, depending on their need.
Need and struggle are what excite and
inspire us.
➤
William James
report erratum • discuss
When multiple threads run as part of a single application, or a JVM, we
have multiple tasks or operations running concurrently. A concurrent appli-
cation makes use of multiple threads or concurrent flows of execution.
On a single processor, these concurrent tasks are often multiplexed or
multitasked. That is, the processor rapidly switches between the context of
each flow of execution. However, only one thread, and hence only one flow
of execution, is performed at any given instance. On a multicore processor,
more than one flow of execution (thread) is performed at any given instance.
That number depends on the number of cores available on the processor,
and the number of concurrent threads for an application depends on the
number of cores associated with its process.
1.2 The Power of Concurrency
We’re interested in concurrency for two reasons: to make an application
responsive/improve the user experience and to make it faster.
Making Apps More Responsive
When we start an application, the main thread of execution often takes on
multiple responsibilities sequentially, depending on the actions we ask it to
perform: receive input from a user, read from a file, perform some calcula-
tions, access a web service, update a database, display a response to the
user, and so on. If each of these operations takes only fractions of a second,
then there may be no real need to introduce additional flows of execution;
a single thread may be quite adequate to meet the needs.
In most nontrivial applications, however, these operations may not be that
quick. Calculations may take anywhere from a couple of seconds to a few
minutes. Requests for data from that web service may encounter network
dela y s, so the th read waits fo r t h e r espon se t o a rriv e . W hile this is h a ppen i ng,
there’s no way for the users of the application to interact with or interrupt
the application because the single thread is held on some operation to finish.
Let’s consider an example that illustrates the need for more than one thread
and how it impacts responsiveness. We often time events, so it would be
nice to have stopwatch application. We can click a button to start the watch,
and it will run until we click the button again. A naively written
1
bit of code
for this is shown next (only the action handler for the button is shown; you
can download the full program from the website for this book):
1. In the examples, we’ll simply let exceptions propagate instead of logging or handling
them—but be sure to handle exceptions properly in your production code.
2 • Chapter 1. The Power and Perils of Concurrency
report erratum • discuss
Download introduction/NaiveStopWatch.java
//This will not work
public void actionPerformed(final ActionEvent event) {
if (running) stopCounting(); else startCounting();
}
private void startCounting() {
startStopButton.setText("Stop");
running = true;
for(int count = 0; running; count++) {
timeLabel.setText(String.format("%d", count));
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
throw new RuntimeException(ex);
}
}
}
private void stopCounting() {
running = false;
startStopButton.setText("Start");
}
When we run the little stopwatch application, a window with a Start button
and a “0” label will appear. Unfortunately, when we click the button, we
won’t see any change—the button does not change to “Stop,” and the label
does not show the time count. What’s worse, the application will not even
respond to a quit request.
The main event dispatch thread is responsible for noticing UI-related events
and delegating actions to be performed. When the Start button is clicked,
the main event dispatch thread went into the event handler
actionPerformed()
;
there it was held hostage by the method
startCounting()
as it started counting.
Now, as we click buttons or try to quit, those events are dropped into the
event queue, but the main thread is too busy and will not respond to those
events—ever.
We need an additional thread, or a timer that in turn would use an additional
thread, to make the application responsive. We need to delegate the task of
counting and relieve the main event dispatch thread of that responsibility.
Not only can threads help make applications responsive, but they can help
enhance the user experience. Applications can look ahead at operations the
user may perform next and carry out the necessary actions, such as indexing
or caching some data the user needs.
report erratum • discuss
The Power of Concurrency • 3
剩余281页未读,继续阅读
Poyy6258
- 粉丝: 0
- 资源: 20
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- C++标准程序库:权威指南
- Java解惑:奇数判断误区与改进方法
- C++编程必读:20种设计模式详解与实战
- LM3S8962微控制器数据手册
- 51单片机C语言实战教程:从入门到精通
- Spring3.0权威指南:JavaEE6实战
- Win32多线程程序设计详解
- Lucene2.9.1开发全攻略:从环境配置到索引创建
- 内存虚拟硬盘技术:提升电脑速度的秘密武器
- Java操作数据库:保存与显示图片到数据库及页面
- ISO14001:2004环境管理体系要求详解
- ShopExV4.8二次开发详解
- 企业形象与产品推广一站式网站建设技术方案揭秘
- Shopex二次开发:触发器与控制器重定向技术详解
- FPGA开发实战指南:创新设计与进阶技巧
- ShopExV4.8二次开发入门:解决升级问题与功能扩展
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功