0

所以我正在根据 MVC Pattern 建立一个网站。我使用 Eclipse/Tomcat。

我有一个 PostAccess 类,它从数据库中检索我的帖子,它创建一个包含 PostBean 项目的向量。servlet 将向量提供给 jsp 文件,而 jsp 文件创建 html 等。

我的问题是不止一个线程与向量交互,所以我在 eclipse 上得到了这个:

java.util.NoSuchElementException
at java.util.Vector$Itr.next(Unknown Source)

正如我从谷歌搜索中了解到的,这个错误是因为没有同步编辑向量的线程。

但是我到底应该在哪里进行同步?

此代码在我的 PostAccess 类中:

public synchronized Vector<Post> RetrievePosts() throws SQLException
{

向量 c = (Vector)(new Vector());return c; }

这是在我的 Servlet 类中:

public synchronized  void process(ServletContext servletContext,HttpServletRequest request, HttpServletResponse response) 
{
    Vector<Post> c = (Vector<Post>)(new Vector<Post>());

    try {
        PostDAO pDAO=new PostDAO(servletContext);

        c=(Vector<Post>) pDAO.RetrievePosts();

    } catch (ClassNotFoundException | SQLException e) {

        e.printStackTrace();
    }
    request.setAttribute("posts", c);
}

这是在我的jsp中:

<% Vector<Post> c =(Vector<Post>)request.getAttribute("posts");

Iterator<Post> i = c.iterator();  
herePost p=(Post)i.next();


                        while (!c.isEmpty()) { %>
4

1 回答 1

0

我不认为两个线程在同一个 Vector 上工作,因为在您显示的代码中 Vector 是在 process 方法中声明的(我假设那是 doGet 调用的那个),因此它是线程私有的处理请求。因此,除非 PostAccess 中发生了一些非常时髦的事情,否则我认为您可以排除线程破坏 Vector 的可能性。

但是,这看起来可能是问题的原因:

Iterator<Post> i = c.iterator();  
herePost p=(Post)i.next();

如果向量一开始是空的,那将导致 java.util.NoSuchElementException 因为 isEmpty() 测试在之后完成。

于 2013-02-05T00:27:05.160 回答