Java 中的同步帮助
查看 http://download.eclipse.org/ jetty/stable-7/xref/com/acme/ChatServlet.html,我似乎不明白为什么在同步方法中需要有同步块,如下所示:
private synchronized void chat(HttpServletRequest request,HttpServletResponse response,String username,String message)
throws IOException
{
Map<String,Member> room=_rooms.get(request.getPathInfo());
if (room!=null)
{
// Post chat to all members
for (Member m:room.values())
{
synchronized (m)
{
m._queue.add(username); // from
m._queue.add(message); // chat
// wakeup member if polling
if (m._continuation!=null)
{
m._continuation.resume();
m._continuation=null;
}
}
}
}
Why does m< /code> 如果整个方法已经是线程安全的,是否需要同步(再次?)?
感谢您的任何见解。
looking at http://download.eclipse.org/jetty/stable-7/xref/com/acme/ChatServlet.html, I don't seem to understand why there needs to be a synchronization block in a synchronized method, like so:
private synchronized void chat(HttpServletRequest request,HttpServletResponse response,String username,String message)
throws IOException
{
Map<String,Member> room=_rooms.get(request.getPathInfo());
if (room!=null)
{
// Post chat to all members
for (Member m:room.values())
{
synchronized (m)
{
m._queue.add(username); // from
m._queue.add(message); // chat
// wakeup member if polling
if (m._continuation!=null)
{
m._continuation.resume();
m._continuation=null;
}
}
}
}
Why does m
need to be synchronized (again?) if the whole method is already thread-safe?
Thank you for any insight.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
同步方法“chat(...)”在其实例对象上同步,而synchronized(m) 在“m”对象上同步 - 因此它们在两个不同的对象上同步。基本上,它是确保其他一些 servlet 对象不会同时干扰同一个成员实例。
The synchronized method "chat(...)" synchronizes on it's instance object whereas the synchronized(m) synchronizes on the "m" object - so they are synchronizing on two different objects. Basically it's making sure that some other servlet object isn't messing with the same Member instance at the same time.
当整个方法同步时,将在
this
对象上获得锁。但同步块仅获取当前迭代中使用的成员的锁。When whole method is synchronized the lock is obtained on the
this
object. But the synchronized block obtains lock only on the member currently being used in iteration.同步是在不同的锁上。
方法定义中的
synchronized
关键字意味着在this
上同步的其他代码不能与该方法并行运行。synchronized(m)
作用域意味着在m
上同步的其他代码无法与循环并行运行。The synchronization is on different locks.
The
synchronized
keyword at the method definition means that other code that synchronizes onthis
cannot run run in parallel to the method.The
synchronized(m)
scope means that other code that synchronizes onm
cannot run in parallel to the loop.