java.io.IOException: Connection is closed

176
14 января 2019, 17:40

При получении данных из БД довольно часто возникает такая ошибка. В чем проблема? Использую среду NetBeans и GlassFish Server

Info:   sql1.toString() = SELECT * FROM workers WHERE profession LIKE '%%' ORDER BY date_create DESC LIMIT 0, 15
Info:   sql1.toString() = SELECT * FROM workers WHERE profession LIKE '%%' ORDER BY date_create DESC LIMIT 0, 15
Info:   sql1.toString() = SELECT * FROM workers WHERE profession LIKE '%%' ORDER BY date_create DESC LIMIT 0, 15
Warning:   StandardWrapperValve[default]: Servlet.service() for servlet default threw exception
java.io.IOException: Connection is closed
    at org.glassfish.grizzly.nio.NIOConnection.assertOpen(NIOConnection.java:432)
    at org.glassfish.grizzly.http.io.OutputBuffer.write(OutputBuffer.java:653)
    at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:355)
    at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:342)
    at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:161)
    at org.apache.catalina.servlets.DefaultServlet.copyRange(DefaultServlet.java:2477)
    at org.apache.catalina.servlets.DefaultServlet.copy(DefaultServlet.java:2212)
    at org.apache.catalina.servlets.DefaultServlet.serveResource(DefaultServlet.java:1085)
    at org.apache.catalina.servlets.DefaultServlet.doGet(DefaultServlet.java:568)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.IOException: Программа на вашем хост-компьютере разорвала установленное подключение
    at sun.nio.ch.SocketDispatcher.write0(Native Method)
    at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:51)
    at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
    at sun.nio.ch.IOUtil.write(IOUtil.java:51)
    at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:471)
    at org.glassfish.grizzly.nio.transport.TCPNIOUtils.flushByteBuffer(TCPNIOUtils.java:149)
    at org.glassfish.grizzly.nio.transport.TCPNIOUtils.writeCompositeBuffer(TCPNIOUtils.java:87)
    at org.glassfish.grizzly.nio.transport.TCPNIOAsyncQueueWriter.write0(TCPNIOAsyncQueueWriter.java:129)
    at org.glassfish.grizzly.nio.transport.TCPNIOAsyncQueueWriter.write0(TCPNIOAsyncQueueWriter.java:106)
    at org.glassfish.grizzly.nio.AbstractNIOAsyncQueueWriter.write(AbstractNIOAsyncQueueWriter.java:260)
    at org.glassfish.grizzly.nio.AbstractNIOAsyncQueueWriter.write(AbstractNIOAsyncQueueWriter.java:169)
    at org.glassfish.grizzly.nio.AbstractNIOAsyncQueueWriter.write(AbstractNIOAsyncQueueWriter.java:71)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransportFilter.handleWrite(TCPNIOTransportFilter.java:126)
    at org.glassfish.grizzly.filterchain.TransportFilter.handleWrite(TransportFilter.java:191)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$8.execute(ExecutorResolver.java:111)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.filterchain.FilterChainContext.write(FilterChainContext.java:890)
    at org.glassfish.grizzly.filterchain.FilterChainContext.write(FilterChainContext.java:858)
    at org.glassfish.grizzly.http.io.OutputBuffer.flushBuffer(OutputBuffer.java:1029)
    at org.glassfish.grizzly.http.io.OutputBuffer.write(OutputBuffer.java:681)
    ... 37 more

Выпрыгивает только два класса, вместо 15. Думал может быть дело в целостности данных. Поизменял данные, ничего не вышло...

Вот исходный код подключения к БД. Должно вытаскивать 15 резюме, в зависимости от выбранной страницы на сайте.

public class ListResume {
    private Map<Integer, Resume> mapResume = new LinkedHashMap<>();
    private int COUNT_RESUME;
    private int PAGE;
    private int NUMBER_START_RESUME;
    private final int SIZE_RESUME_LIST = 15;
    private void setPage(int page) {
        this.PAGE = page;
        this.NUMBER_START_RESUME = this.SIZE_RESUME_LIST * (this.PAGE-1);
    }
    private Map<Integer, Resume> search(String sqlGetItems, String sqlGetCount) {        
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DataBase.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sqlGetItems);
            while (resultSet.next()) {
                Resume resume = new Resume();
                resume.setIdResume(resultSet.getInt("id_resume"));
                resume.setImage(resultSet.getBytes("image"));
                resume.setProfession(resultSet.getString("profession"));
                resume.setWages(resultSet.getDouble("wages"));
                resume.setTypeWages(resultSet.getString("type_wages"));
                resume.setEducation(resultSet.getString("education")); 
                resume.setExperienceYear(resultSet.getInt("experience_years"));
                resume.setExperienceMouth(resultSet.getInt("experience_mouths"));
                mapResume.put(resume.getIdResume(), resume);
            }
            resultSet = statement.executeQuery(sqlGetCount);
            while (resultSet.next()) {COUNT_RESUME = resultSet.getInt(1);}
        } catch (SQLException ex) {
            Logger.getLogger(Resume.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (statement!=null) statement.close();
                if (resultSet!=null) resultSet.close();
                if (connection!=null) connection.close();
            } catch (SQLException ex) {
                Logger.getLogger(Resume.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return mapResume;
    }
    public Map<Integer, Resume> getResumeNull(int page) {
        if (page != 0) {setPage(page);} else {NUMBER_START_RESUME = 0;}
        String sql1 = "SELECT * FROM workers ORDER BY date_create "
                + "DESC LIMIT "+this.NUMBER_START_RESUME+", "+this.SIZE_RESUME_LIST;
        String sql2 = "SELECT COUNT(*) FROM workers ORDER BY date_create";
        return search(sql1, sql2);
    }
    public Map<Integer, Resume> getResumeSearch(String word, int page) {
        if (page != 0) {setPage(page);} else {NUMBER_START_RESUME = 0;}
        StringBuilder sql1 = new StringBuilder();
        sql1.append("SELECT * FROM workers ");
        sql1.append("WHERE profession LIKE '%" + word + "%' ");
        sql1.append("ORDER BY date_create DESC ");
        sql1.append("LIMIT "+this.NUMBER_START_RESUME+", "+this.SIZE_RESUME_LIST);
        StringBuilder sql2 = new StringBuilder();
        sql2.append("SELECT COUNT(*) FROM workers ");
        sql2.append("WHERE profession LIKE '%" + word + "%'");
        System.out.println("sql1.toString() = "+sql1.toString());
        return search(sql1.toString(), sql2.toString());
    }
    public int getCount() {return COUNT_RESUME;}
}

В чем проблема ума не приложу. Коннектионы закрываю. Был вариант что сам GlassFish ограничивает подключения, проверили на боевом сервере, не в этом дело оказалось. Эксепшен все равно выбивает. Подскажите где ошибка может быть?

Вот на всякий случай сам класс:

public class Resume {
    private int idResume;
    private byte[] image;
    private String profession;
    private double wages;
    private String typeWages;
    private String education;
    private int yearExperience;
    private int mouthExperience;
    private int rating;
    public int getIdResume() {
        return idResume;
    }
    public void setIdResume(int idResume) {
        this.idResume = idResume;
    }
    public byte[] getImage() {
        return image;
    }
    public void setImage(byte[] image) {
        this.image = image;
    }
    public String getProfession() {
        return profession;
    }
    public void setProfession(String profession) {
        this.profession = profession;
    }
    public double getWages() {
        return wages;
    }
    public void setWages(double wages) {
        this.wages = wages;
    }
    public int getRating() {
        return rating;
    }
    public void setRating(int rating) {
        this.rating = rating;
    }
    public String getTypeWages() {
        return typeWages;
    }
    public void setTypeWages(String typeWages) {
        this.typeWages = typeWages;
    }
    public String getEducation() {
        if (education != null) {if (education.length() < 1) {return null;}}
        return education;
    }
    public void setEducation(String education) {
        this.education = education;
    }
    public int getExperienceYears() {
        return yearExperience;
    }
    public void setExperienceYear(int yearExperience) {
        this.yearExperience = yearExperience;
    }
    public int getExperienceMouths() {
        return mouthExperience;
    }
    public void setExperienceMouth(int mouthExperience) {
        if (mouthExperience >= 12) {mouthExperience = 11;}
        this.mouthExperience = mouthExperience;
    }
    public Resume() {
    }
}
READ ALSO
Объединение нескольких запросов в один

Объединение нескольких запросов в один

Можно ли из 3 разных запросов объединить в один, если они не связаны? Чтобы в одном select была примерно такая информация:

168
Функция для разности timestamp - timestamp

Функция для разности timestamp - timestamp

Есть табличка events, в нее пишутся все события связанные с обьектом, структура следующая: id, object_id, timestamp, event_type, action

171
Изменения без перезагрузки

Изменения без перезагрузки

Допустим у меня есть файл testhtml

161
Оцените код верстки блока по сетке

Оцените код верстки блока по сетке

Написал вот такой страшненький код:

208