在java restful api中查找内存泄漏
我是一个有志于学习的业余编程爱好者,但我遇到了一种新的问题,我甚至不知道从哪里开始寻找——java中的内存泄漏。我四处寻找,找不到任何对我有帮助的东西。我使用了TomcatV9.0和Java1.8。我甚至不知道你需要看什么代码才能提供帮助 当我试图向我的REST api发送请求时,我收到此警告在java restful api中查找内存泄漏,java,rest,tomcat,memory-leaks,java-memory-leaks,Java,Rest,Tomcat,Memory Leaks,Java Memory Leaks,我是一个有志于学习的业余编程爱好者,但我遇到了一种新的问题,我甚至不知道从哪里开始寻找——java中的内存泄漏。我四处寻找,找不到任何对我有帮助的东西。我使用了TomcatV9.0和Java1.8。我甚至不知道你需要看什么代码才能提供帮助 当我试图向我的REST api发送请求时,我收到此警告 VARNING: The web application [School] appears to have started a thread named [pool-2-thread-1] but has
VARNING: The web application [School] appears to have started a thread named [pool-2-thread-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
sun.misc.Unsafe.park(Native Method)
java.util.concurrent.locks.LockSupport.parkNanos(Unknown Source)
java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(Unknown Source)
java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(Unknown Source)
java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(Unknown Source)
java.util.concurrent.ThreadPoolExecutor.getTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
服务器可以处理一个或两个请求,然后就停止了。因为我对这类问题还不熟悉,所以我不知道是什么原因造成的,而且四处搜索对我的业余生活也没有什么帮助。我猜我是在以某种方式创建线程,但它们并没有被关闭
我试图用get方法联系的控制器
package se.consys.controllers;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.persistence.NoResultException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.PATCH;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import se.consys.Entities.Course;
import se.consys.Entities.Lecture;
import se.consys.Entities.Student;
import se.consys.Entities.Teacher;
import se.consys.Utilities.HibernateUtility;
import se.consys.dataaccess.DaoGenericHibernateImpl;
import se.consys.params.LocalDateParam;
import se.consys.params.LocalDateTimeParam;
import se.consys.params.MapHelper;
import se.consys.services.GenericService;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@SuppressWarnings("rawtypes, unchecked")
@Path("courses")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class CourseController {
private GenericService courseService = GenericService.getGenericService(new DaoGenericHibernateImpl<>(Course.class));
private GenericService teacherService = GenericService.getGenericService(new DaoGenericHibernateImpl<>(Teacher.class));
private GenericService studentService = GenericService.getGenericService(new DaoGenericHibernateImpl<>(Student.class));
private String noCourseFoundMsg = "No course found with the specified id.";
@GET
public Response getAll() {
List<Course> courses = courseService.findAll();
return Response.status(200).build();
}
@GET
@Path("/{id}")
public Response getById(@PathParam("id") int id) {
try {
Course course = (Course) courseService.findById(id);
return Response.ok().entity(course).build();
} catch (NoResultException e) {
System.out.println(noCourseFoundMsg);
return Response.status(204).build();
}
}
@SuppressWarnings("unchecked")
@POST
public Response create(Course entity) {
courseService.create(entity);
return Response.status(201).entity(entity).build();
}
@PATCH
@Path("/{id}")
public Response partialUpdate(@DefaultValue("0") @PathParam("id") int id,
@DefaultValue("null") @QueryParam("name") String courseName,
@DefaultValue("-1") @QueryParam("duration") int durationInMonths,
@DefaultValue("") @QueryParam("end") LocalDateParam endDate,
@DefaultValue("") @QueryParam("start") LocalDateParam startDate,
@DefaultValue("") @QueryParam("timestamp") LocalDateTimeParam timeStamp,
@DefaultValue("-1") @QueryParam("supervisor") int supervisor)
{
Course courseToBeUpdated = (Course) courseService.findById(id);
System.out.println(courseName);
if (courseName != null) courseToBeUpdated.setCourseName(courseName);
if (durationInMonths != -1) courseToBeUpdated.setDurationInMonths(durationInMonths);
if (endDate != null && !endDate.getLocalDate().equals(LocalDate.MIN)) courseToBeUpdated.setEndDate(endDate.getLocalDate());
if (startDate != null && !startDate.getLocalDate().equals(LocalDate.MIN)) courseToBeUpdated.setStartDate(startDate.getLocalDate());
if (timeStamp != null && !timeStamp.getLocalDateTime().equals(LocalDateTime.MIN)) courseToBeUpdated.setTimeStamp(timeStamp.getLocalDateTime());
if (supervisor != -1) courseToBeUpdated.setSupervisor((Teacher) teacherService.findById(supervisor));
courseService.update(courseToBeUpdated);
return Response.status(200).build();
}
@PATCH
@Path("/{id}/students")
public Response partialUpdateOnStudents(
@DefaultValue("0") @PathParam("id") int id,
@DefaultValue("null") @QueryParam("update") String studentString) {
String[] seperatedIds = studentString.split("-");
List<Integer> studentIds = new ArrayList<Integer>();
for (int i = 0; i < seperatedIds.length; i++) {
studentIds.add((int) Integer.parseInt(seperatedIds[i]));
}
List<Student> allStudents = studentService.findAll();
List<Student> StudentsToAddIntoCourse = new ArrayList<Student>();
for (int i = 0; i < allStudents.size(); i++) {
for(int j = 0; j < studentIds.size(); j++) {
if (allStudents.get(i).getId() == studentIds.get(j)) {
StudentsToAddIntoCourse.add(allStudents.get(i));
}
}
}
Course courseToBeUpdated = (Course) courseService.findById(id);
if (studentString != null) courseToBeUpdated.setStudents(StudentsToAddIntoCourse);
courseService.update(courseToBeUpdated);
return Response.status(200).build();
}
@PUT
@Path("/{id}")
public Response update(@DefaultValue("0") @PathParam("id") int id, Course entity) {
try {
Course courseToBeUpdated = (Course) courseService.findById(id);
courseToBeUpdated.setCourseName(entity.getCourseName());
courseToBeUpdated.setDurationInMonths(entity.getDurationInMonths());
courseToBeUpdated.setEndDate(entity.getEndDate());
courseToBeUpdated.setScheduledLectures(entity.getScheduledLectures());
courseToBeUpdated.setStartDate(entity.getStartDate());
courseToBeUpdated.setStudents(entity.getStudents());
courseToBeUpdated.setSupervisor(entity.getSupervisor());
courseToBeUpdated.setTimeStamp(entity.getTimeStamp());
courseService.update(courseToBeUpdated);
return Response.status(200).entity(entity).build();
} catch (NoResultException e) {
System.out.println(noCourseFoundMsg);
return Response.ok().status(204).build();
}
}
@DELETE
@Path("/{id}")
public Response delete(@DefaultValue("0") @PathParam("id") int id) {
try {
Course courseToBeDeleted = (Course) courseService.findById(id);
courseService.delete(courseToBeDeleted);
return Response.status(200).build();
} catch (NoResultException e) {
System.out.println(noCourseFoundMsg);
return Response.status(204).build();
}
}
}
封装se.consys.controllers;
导入javax.ws.rs.core.MediaType;
导入javax.ws.rs.core.Response;
导入javax.ws.rs.core.Response.Status;
导入javax.persistence.NoResultException;
导入javax.ws.rs.Consumes;
导入javax.ws.rs.DELETE;
导入javax.ws.rs.DefaultValue;
导入javax.ws.rs.GET;
导入javax.ws.rs.PATCH;
导入javax.ws.rs.POST;
导入javax.ws.rs.PUT;
导入javax.ws.rs.Path;
导入javax.ws.rs.PathParam;
导入javax.ws.rs.products;
导入javax.ws.rs.QueryParam;
导入se.consys.Entities.Course;
导入se.consys.Entities.讲座;
导入se.consys.Entities.Student;
导入se.consys.Entities.Teacher;
导入se.consys.Utilities.hibernature;
导入se.consys.dataaccess.daogenerichbernatepimpl;
导入se.consys.params.LocalDateParam;
导入se.consys.params.LocalDateTimeParam;
导入se.consys.params.MapHelper;
导入se.consys.services.GenericService;
导入java.time.LocalDate;
导入java.time.LocalDateTime;
导入java.util.ArrayList;
导入java.util.Date;
导入java.util.List;
导入java.util.Map;
@SuppressWarnings(“原始类型,未选中”)
@路径(“课程”)
@产生(MediaType.APPLICATION_JSON)
@使用(MediaType.APPLICATION_JSON)
公共类课程控制器{
private-GenericService-courseService=GenericService.getGenericService(新的daogenerichbernateimpl(Course.class));
private GenericService teacherService=GenericService.getGenericService(新的daogenerichbernateimpl(Teacher.class));
private GenericService studentService=GenericService.getGenericService(新的daogenerichbernateimpl(Student.class));
私有字符串noCourseFoundMsg=“未找到具有指定id的课程”;
@得到
公众回应getAll(){
列出课程=courseService.findAll();
返回Response.status(200.build();
}
@得到
@路径(“/{id}”)
公共响应getById(@PathParam(“id”)int-id){
试一试{
Course课程=(Course)courseService.findById(id);
返回Response.ok().entity(course.build();
}捕获(noresulte异常){
System.out.println(noCourseFoundMsg);
返回Response.status(204.build();
}
}
@抑制警告(“未选中”)
@职位
公共响应创建(课程实体){
courseService.create(实体);
返回Response.status(201).entity(entity.build();
}
@补丁
@路径(“/{id}”)
公共响应部分更新(@DefaultValue(“0”)@PathParam(“id”)int-id,
@DefaultValue(“null”)@QueryParam(“name”)字符串courseName,
@DefaultValue(“-1”)@QueryParam(“duration”)int DurationInMonts,
@DefaultValue(“”@QueryParam(“结束”)LocalDateParam endDate,
@DefaultValue(“”@QueryParam(“开始”)LocalDateParam startDate,
@DefaultValue(“”@QueryParam(“时间戳”)LocalDateTimeParam时间戳,
@DefaultValue(“-1”)@QueryParam(“主管”)int-supervisor)
{
Course courseToBeUpdated=(Course)courseService.findById(id);
系统输出打印号(courseName);
如果(courseName!=null)courseToBeUpdated.setCourseName(courseName);
如果(DurationInMonts!=-1)要更新的课程。设置DurationInMonts(DurationInMonts);
如果(endDate!=null&&!endDate.getLocalDate().equals(LocalDate.MIN))courseToBeUpdated.setEndDate(endDate.getLocalDate());
如果(startDate!=null&&!startDate.getLocalDate().equals(LocalDate.MIN))courseToBeUpdated.setStartDate(startDate.getLocalDate());
如果(timeStamp!=null&&!timeStamp.getLocalDateTime().equals(LocalDateTime.MIN))courseToBeUpdated.setTimeStamp(timeStamp.getLocalDateTime());
if(supervisor!=-1)courseToBeUpdated.setSupervisor((教师)teacherService.findById(supervisor));
courseService.update(CourseToBeUpdate);
返回Response.status(200.build();
}
@补丁
@路径(“/{id}/students”)
公众响应部分更新学生(
@DefaultValue(“0”)@PathParam(“id”)int-id,
@DefaultValue(“null”)@QueryParam(“更新”)字符串studentString){
String[]separateddids=studentString.split(“-”);
List studentId=new ArrayList();
for(int i=0;ipackage se.consys.dataaccess;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import org.hibernate.Session;
import se.consys.Utilities.Helper;
import se.consys.Utilities.HibernateUtility;
import se.consys.services.GenericService;
public class DaoGenericHibernateImpl<T extends Serializable> implements IGenericDao<T> {
Session session = HibernateUtility.getSessionFactory().openSession();
private String activeClassName;
private String wrongClassError = "ERROR: Wrong class used on the established service.";
public DaoGenericHibernateImpl(Class<T> type) {
activeClassName = type.getSimpleName();
}
@Override
public void create(T entity) {
if (entity.getClass().getSimpleName().equals(activeClassName)) {
session.beginTransaction();
session.persist(entity);
session.getTransaction().commit();
} else {
System.out.println(wrongClassError + " Entity has not been saved to the database. "
+ "Class used: " + entity.getClass().getSimpleName() + ". "
+ "Class expected: " + activeClassName + ".");
}
}
@Override
public T update(T entity) {
if (entity.getClass().getSimpleName().equals(activeClassName)) {
session.beginTransaction();
session.merge(entity);
session.getTransaction().commit();
return entity;
} else {
System.out.println(wrongClassError + " Entity has not been updated. "
+ "Class used: " + entity.getClass().getSimpleName() + ". "
+ "Class expected: " + activeClassName + ".");
}
return entity;
}
@Override
public void delete(T entity) {
if (entity.getClass().getSimpleName().equals(activeClassName)) {
session.beginTransaction();
//session.update(entity);
session.delete(entity);
session.getTransaction().commit();
} else {
System.out.println(wrongClassError + " Entity has not been deleted. "
+ "Class used: " + entity.getClass().getSimpleName() + ". "
+ "Class expected: " + activeClassName + ".");
}
}
@Override
public T findById(int id) {
final String HQL_BY_ID = "FROM " + activeClassName + " WHERE id=:id";
@SuppressWarnings("unchecked")
T result = (T) session.createQuery(HQL_BY_ID)
.setParameter("id", id)
.setMaxResults(1)
.getSingleResult();
return result;
}
@Override
public List<T> findAll() {
String HQL_FIND_ALL = "FROM " + activeClassName;
@SuppressWarnings("unchecked")
List<T> result = (List<T>) session.createQuery(HQL_FIND_ALL)
.getResultList();
return result;
}
@Override
public void removeReference(T entity, Class<?> reference) {
Method setter = Helper.findSetter(entity, reference);
try {
setter.invoke(entity, null);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e.getMessage());
}
}
}