Runnable 中抛出java.lang.ArrayIndexOutOfBoundsException: -1

[已解决] SimpleDateFormat.format并发调用会有问题private SimpleDateFormat.StringBuffer format(Date date, StringBuffer toAppendTo, FieldDelegate delegate) 里面用了calendar.setTime(date);这玩意是全局的,后面还会调用它,所以并发时候会出问题。
Random中protected Random.next(int bits);采用AtomicLong的CAS操作并发时候不会出问题。


每个Task有自己的ArrayList实例,在多线程情况下每个ArrayList实例应该不存在并发写入啊,为没什么还报ArrayIndexOutOfBoundsException: -1
求助大神,网上找了好久没结果。


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static java.lang.System.out;

public class TestArrayList {

    public static void main(String[] args){
        TestArrayList t= new TestArrayList();
        t.testInsertRows();
    }

    private static int millisecondOf1Day= 1000*3600*24;
    private static int millisecondOf5Min= 1000*60*5;
    private static final SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private final ExecutorService pool= Executors.newFixedThreadPool(8);

    public void testInsertRows(){
        Random random= new Random();
        int taskId= 0;
        for(int i=0; i< 8; i++){
            taskId++;
            pool.submit(new Task(taskId, 10000, null));
        }
        out.println("all submited!");
    }

    static class Task implements Runnable{
        private Integer id;
        private List<Bean> list;
        private int rowCount;
        private int count=0;
        private Random random;

        public Task(Integer id, Integer rowCount, Random random){
            this.id= id;
            this.list= new ArrayList<>(rowCount+1);
            this.rowCount= rowCount;
//          this.random= random;
            this.random= new Random();
        }

        @Override
        public void run() {
            out.println("task:"+id+" is running! "+Thread.currentThread());
            try{
                for(int j=0; j< rowCount; j++ ){
                    Long randomTime= random.nextLong();
                    Date validityDate= new Date(randomTime- millisecondOf1Day),
                            startDate= new Date(randomTime),
                            endDate= new Date(randomTime+ 2*millisecondOf1Day);
                    Bean bean = new Bean();
                    bean.setField0("K0000033");
                    bean.setField1("0001");
                    bean.setField2(sdf.format(validityDate));
                    bean.setField3(new Double(0.0).toString());
                    bean.setField4(sdf.format(startDate));
                    bean.setField5(sdf.format(endDate));
                    list.add(bean);
                }
                out.println("list is prepared in thread:"+id);
                Thread.sleep(millisecondOf5Min);//
                out.println(count+" rows has been inserted in thread:"+id); 
            }catch (Exception e) {
                synchronized (out) {                    
                    out.println("task:"+id+" in error"+Thread.currentThread());
                    e.printStackTrace();
                    out.println("task:"+id+" error info print completed");
                }
            }
        }
    }

}

class Bean{
    private String field0;
    private String field1;
    private String field2;
    private String field3;
    private String field4;
    private String field5;
    private String field6;
    /**
     * @return the field0
     */
    public String getField0() {
        return field0;
    }
    /**
     * @param field0 the field0 to set
     */
    public void setField0(String field0) {
        this.field0 = field0;
    }
    /**
     * @return the field1
     */
    public String getField1() {
        return field1;
    }
    /**
     * @param field1 the field1 to set
     */
    public void setField1(String field1) {
        this.field1 = field1;
    }
    /**
     * @return the field2
     */
    public String getField2() {
        return field2;
    }
    /**
     * @param field2 the field2 to set
     */
    public void setField2(String field2) {
        this.field2 = field2;
    }
    /**
     * @return the field3
     */
    public String getField3() {
        return field3;
    }
    /**
     * @param field3 the field3 to set
     */
    public void setField3(String field3) {
        this.field3 = field3;
    }
    /**
     * @return the field4
     */
    public String getField4() {
        return field4;
    }
    /**
     * @param field4 the field4 to set
     */
    public void setField4(String field4) {
        this.field4 = field4;
    }
    /**
     * @return the field5
     */
    public String getField5() {
        return field5;
    }
    /**
     * @param field5 the field5 to set
     */
    public void setField5(String field5) {
        this.field5 = field5;
    }
    /**
     * @return the field6
     */
    public String getField6() {
        return field6;
    }
    /**
     * @param field6 the field6 to set
     */
    public void setField6(String field6) {
        this.field6 = field6;
    }
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Bean [field0=" + field0 + ", field1=" + field1 + ", field2=" + field2 + ", field3=" + field3
                + ", field4=" + field4 + ", field5=" + field5 + ", field6=" + field6 + "]";
    }
}

task:1 is running! Thread[pool-1-thread-1,5,main]
task:4 is running! Thread[pool-1-thread-4,5,main]
task:3 is running! Thread[pool-1-thread-3,5,main]
task:2 is running! Thread[pool-1-thread-2,5,main]
task:5 is running! Thread[pool-1-thread-5,5,main]
task:6 is running! Thread[pool-1-thread-6,5,main]
all submited!
task:7 is running! Thread[pool-1-thread-7,5,main]
task:8 is running! Thread[pool-1-thread-8,5,main]
task:7 in errorThread[pool-1-thread-7,5,main]
java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Calendar.getDisplayName(Unknown Source)
at java.text.SimpleDateFormat.subFormat(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.DateFormat.format(Unknown Source)
at com.haimian.test.concurrent.TestArrayList$Task.run(TestArrayList.java:64)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
task:7 error info print completed
task:8 in errorThread[pool-1-thread-8,5,main]
java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Calendar.getDisplayName(Unknown Source)
at java.text.SimpleDateFormat.subFormat(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.DateFormat.format(Unknown Source)
at com.haimian.test.concurrent.TestArrayList$Task.run(TestArrayList.java:65)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
task:8 error info print completed
task:4 in errorThread[pool-1-thread-4,5,main]
java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Calendar.getDisplayName(Unknown Source)
at java.text.SimpleDateFormat.subFormat(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.DateFormat.format(Unknown Source)
at com.haimian.test.concurrent.TestArrayList$Task.run(TestArrayList.java:62)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
task:4 error info print completed
task:1 in errorThread[pool-1-thread-1,5,main]
java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Calendar.getDisplayName(Unknown Source)
at java.text.SimpleDateFormat.subFormat(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.DateFormat.format(Unknown Source)
at com.haimian.test.concurrent.TestArrayList$Task.run(TestArrayList.java:64)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
task:1 error info print completed
task:5 in errorThread[pool-1-thread-5,5,main]
java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Calendar.getDisplayName(Unknown Source)
at java.text.SimpleDateFormat.subFormat(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.DateFormat.format(Unknown Source)
at com.haimian.test.concurrent.TestArrayList$Task.run(TestArrayList.java:65)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
task:5 error info print completed
task:3 in errorThread[pool-1-thread-3,5,main]
java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Calendar.getDisplayName(Unknown Source)
at java.text.SimpleDateFormat.subFormat(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.DateFormat.format(Unknown Source)
at com.haimian.test.concurrent.TestArrayList$Task.run(TestArrayList.java:64)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
task:3 error info print completed
task:6 in errorThread[pool-1-thread-6,5,main]
java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Calendar.getDisplayName(Unknown Source)
at java.text.SimpleDateFormat.subFormat(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.DateFormat.format(Unknown Source)
at com.haimian.test.concurrent.TestArrayList$Task.run(TestArrayList.java:64)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
task:6 error info print completed
list is prepared in thread:2

yhk1996
needRestart protected Random.next(int bits);采用AtomicLong的CAS操作
大约一年之前 回复
yhk1996
needRestart private SimpleDateFormat.StringBuffer format(Date date, StringBuffer toAppendTo, FieldDelegate delegate) 里面用了calendar.setTime(date);这玩意是全局的估计在这就出毛病了
大约一年之前 回复

2个回答

Random 不要公用,改为线程内新建再试试

yhk1996
needRestart 了解了,之前是看别人也用单例才把random用单例的。原来这个采纳后就不能修改了……
大约一年之前 回复
weixin_39606236
꧁gaoKuo꧂ 回复GaoKuoZ: 看了下文档,我Random也理解错了 java.util.Random的java.util.Random是线程安全的。 但是,跨线程的同时使用java.util.Random实例可能会遇到争用,从而导致性能下降。
大约一年之前 回复
weixin_39606236
꧁gaoKuo꧂ 回复needRestart: 我都没看到sdf.... Random也不要线程共享哦
大约一年之前 回复
yhk1996
needRestart 感谢大佬提醒
大约一年之前 回复
yhk1996
needRestart 破案了……是simpleDateFormat被多线程调用出的错,Random不会出并发错误。之前报错的行数是乱的也一直没注意这个。
大约一年之前 回复
yhk1996
needRestart 是结束
大约一年之前 回复
yhk1996
needRestart 我把cache打印时候加锁了,保证出错时候只有一个线程打印输出,"task:n in error…"是开始,"task:n error info…
大约一年之前 回复
weixin_39606236
꧁gaoKuo꧂ 回复needRestart: 错误信息发一下 全部的
大约一年之前 回复
yhk1996
needRestart 刚试了还是一样的……吐血啊,上Google也搜了,就是没找到相关的。
大约一年之前 回复

线程中用了那么多的成员变量,这种很容易出现线程数据的问题,就好比卖火车票一样,要考虑线程的安全性的

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Kettle连接mysql数据库报错Failed to execute runnable (java.lang.NullPointerException)

Kettle连接mysql数据库点击确认时报错Failed to execute runnable (java.lang.NullPointerException)该怎么办呀 ![图片说明](https://img-ask.csdn.net/upload/202004/24/1587710084_31337.jpg)

java.lang.NoClassDefFoundError 不是环境变量

原码 import java.awt.*; import java.awt.event.*; public class TankClient extends Frame { int x = 50, y = 50; @Override public void paint(Graphics g) { Color c = g.getColor(); g.setColor(Color.RED); g.fillOval(50, 50, 30, 30); y += 5; } public void lauchFrame() { this.setLocation(400, 300); this.setSize(800, 600); this.setTitle("TankWar"); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); this.setResizable(false); this.setBackground(Color.GREEN); setVisible(true); new Thread(new PaintThread()).start(); } public static void main(String[] args) { TankClient tc = new TankClient(); tc.lauchFrame(); } private class PaintThread implements Runnable{ @Override public void run() { repaint(); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } }} } 问题 Exception in thread "main" java.lang.NoClassDefFoundError: TankClient$PaintThread at TankClient.lauchFrame(TankClient.java:27) at TankClient.main(TankClient.java:32) Caused by: java.lang.ClassNotFoundException: TankClient$PaintThread at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:252) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) ... 2 more

springmvc 实现文件下载 出现异常java.lang.OutOfMemoryError: Java heap space

网上找解决方案,一般都是tomcat中添加-Xms256m -Xms512m等配置,但是不行啊。 我的是MyEclipse里的tomcat。 下载20M(包括)以内的文件没问题,超过就会报异常,有什么解决办法吗? 还有是不是请求下载文件时,服务器会把文件全部装入内存再发过来,还是分成多个部分发送,超过内存大小的文件如何发送呢? ** *--异常信息* ** type Exception report message description The server encountered an internal error () that prevented it from fulfilling this request. exception org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.OutOfMemoryError: Java heap space org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1259) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827) javax.servlet.http.HttpServlet.service(HttpServlet.java:690) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812) javax.servlet.http.HttpServlet.service(HttpServlet.java:803) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) root cause java.lang.OutOfMemoryError: Java heap space org.apache.commons.io.output.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:324) org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:361) org.apache.commons.io.FileUtils.readFileToByteArray(FileUtils.java:1360) com.ysm.ysite.controller.Test.fileDownload(Test.java:60) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176) org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440) org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827) javax.servlet.http.HttpServlet.service(HttpServlet.java:690) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812) javax.servlet.http.HttpServlet.service(HttpServlet.java:803) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) note The full stack trace of the root cause is available in the Apache Tomcat/6.0.13 logs.

测试第三方提供的接口,运行报错java.lang.AbstractMethodError如何解决

2016-05-24 09:08:12.918::WARN: Nested in org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.AbstractMethodError: javax.ws.rs.core.UriBuilder.uri(Ljava/lang/String;)Ljavax/ws/rs/core/UriBuilder;: java.lang.AbstractMethodError: javax.ws.rs.core.UriBuilder.uri(Ljava/lang/String;)Ljavax/ws/rs/core/UriBuilder; at javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:119) at org.glassfish.jersey.client.JerseyWebTarget.<init>(JerseyWebTarget.java:71) at org.glassfish.jersey.client.JerseyClient.target(JerseyClient.java:290) at org.glassfish.jersey.client.JerseyClient.target(JerseyClient.java:76) at client.api.internal.util.WebUtils.doPost(WebUtils.java:57) at client.api.DefaultZJSClient.doPost(DefaultZJSClient.java:264) at client.api.DefaultZJSClient._execute(DefaultZJSClient.java:180) at client.api.DefaultZJSClient.execute(DefaultZJSClient.java:118) at com.epoch.cc.totoo.totto.testTotto(totto.java:33) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at javax.servlet.http.HttpServlet.service(HttpServlet.java:820) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1093) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084) at com.epoch.framework.web.LoginFilter.doFilter(LoginFilter.java:175) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:360) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:712) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405) at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:211) at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:139) at org.mortbay.jetty.Server.handle(Server.java:313) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:506) at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:830) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:514) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:381) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:396) at org.mortbay.thread.BoundedThreadPool$PoolThread.run(BoundedThreadPool.java:442) 2016-05-24 09:08:12.933::WARN: /e7cc/Totto/testTotto.do

写网上商城作业java.lang.NullPointerException

1. 报错的:HTTP Status 500 - -------------------------------------------------------------------------------- type Exception report message description The server encountered an internal error that prevented it from fulfilling this request. exception java.lang.NullPointerException com.eshore.action.GoodServlet.doPost(GoodServlet.java:56) com.eshore.action.GoodServlet.doGet(GoodServlet.java:26) javax.servlet.http.HttpServlet.service(HttpServlet.java:621) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) com.eshore.filters.EncodeFilter.doFilter(EncodeFilter.java:45) note The full stack trace of the root cause is available in the Apache Tomcat/7.0.30 logs. -------------------------------------------------------------------------------- Apache Tomcat/7.0.30 **2.goodservlet代码** package com.eshore.action; import java.io.IOException; import java.util.Vector; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.eshore.factory.DAOFactory; import com.eshore.pojo.Goods; /** * 商品的Servlet类 */ @WebServlet( urlPatterns = { "/goods" }, name = "goodsServlet" ) public class GoodServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //判断action类型 String action=request.getParameter("action"); String path=null; Vector<Goods> gVector=new Vector<Goods>(); try{ if(action.equals("index-select")){//查询商品列表 String keyWord=request.getParameter("keyWord");//获取查询的输入值 String keyClass=request.getParameter("keyClass");//获取查询类别 gVector=DAOFactory.getGoodDAOInstance().//获得所有商品 queryAll(keyWord, keyClass); request.setAttribute("goods", gVector); path="goods/goodslist.jsp"; }else if(action.equals("goodslist-select")){//指定商品列表 Goods good=new Goods(); String sid=request.getParameter("sid");//获得商品的id gVector=DAOFactory.getGoodDAOInstance().//获得指定的商品对象 queryGoodBySid(Integer.valueOf(sid)); if(gVector.size()>0&&gVector!=null) good =(Goods)gVector.get(0); request.setAttribute("good", good); path="goods/good.jsp"; } }catch(Exception e){ e.printStackTrace(); } request.getRequestDispatcher(path).forward(request, response); } }

mybatis与struts1 [java.lang.NoClassDefFoundError:org/apache/ibatis/io/Resources]

在Action中,当我要向数据库中插入一条记录时,报了下面的错误: [code="java"] javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/apache/ibatis/io/Resources org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:294) org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187) com.zrxx.action.ProjectAction.execute(ProjectAction.java:33) org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431) org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) javax.servlet.http.HttpServlet.service(HttpServlet.java:637) javax.servlet.http.HttpServlet.service(HttpServlet.java:717) java.lang.NoClassDefFoundError: org/apache/ibatis/io/Resources com.zrxx.util.SqlSessionFactoryTool.getSqlSessionFactory(SqlSessionFactoryTool.java:30) com.zrxx.dao.BaseDao.openSession(BaseDao.java:15) com.zrxx.dao.BaseDao.openSession(BaseDao.java:10) com.zrxx.dao.ProjectDao.insertPro(ProjectDao.java:13) com.zrxx.action.ProjectAction.add(ProjectAction.java:54) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270) org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187) com.zrxx.action.ProjectAction.execute(ProjectAction.java:33) org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431) org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) javax.servlet.http.HttpServlet.service(HttpServlet.java:637) javax.servlet.http.HttpServlet.service(HttpServlet.java:717) [/code] 这个错误是当dao对象已经创建了,调用dao.insert()时发出的 附上我的SqlSessionFactoryTool源代码: [code="java"] public class SqlSessionFactoryTool { private static SqlSessionFactoryTool tool; private SqlSessionFactory factory; public static SqlSessionFactoryTool getInstance(){ if(tool == null) tool = new SqlSessionFactoryTool(); return tool; } public SqlSessionFactory getSqlSessionFactory(){ String resource = "/mybatis.xml"; Reader reader = null; try { reader = Resources.getResourceAsReader(resource); } catch (IOException e) { e.printStackTrace(); } factory = new SqlSessionFactoryBuilder().build(reader); return factory; } [/code] 这是我的目录结构 [img]http://dl.iteye.com/upload/attachment/597707/8f659481-6204-34e4-9c24-18ba93290695.png[/img]

java.lang.AbstractMethodError

开发的时候 在程序里面 加了一个方法 就报这个错,这个方法所加的 地方是打成一个jar 放在项目中的,类似 分布式里面的 接口jar , 这个方法是按照 程序里面类似的方法加的, 那个方法不报错 ,这个报错 ,为什么呢。而且 本地 是ok的 一到服务器 就报这个错。

springboot security oauth2 报错 java.lang.IllegalArgumentException: URI must not be null

``` 2018-11-14 17:12:11.816 [http-nio-8081-exec-1] WARN o.s.s.o.p.token.RemoteTokenServices-Null Client ID or Client Secret detected. Endpoint that requires authentication will reject request with 401 error. 2018-11-14 17:12:11.823 [http-nio-8081-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet]-Servlet.service() for servlet [dispatcherServlet] in context with path [/smartHome] threw exception java.lang.IllegalArgumentException: URI must not be null at org.springframework.util.Assert.notNull(Assert.java:193) at org.springframework.web.util.UriComponentsBuilder.fromUriString(UriComponentsBuilder.java:197) at org.springframework.web.util.DefaultUriBuilderFactory$DefaultUriBuilder.initUriComponentsBuilder(DefaultUriBuilderFactory.java:218) at org.springframework.web.util.DefaultUriBuilderFactory$DefaultUriBuilder.<init>(DefaultUriBuilderFactory.java:214) at org.springframework.web.util.DefaultUriBuilderFactory.uriString(DefaultUriBuilderFactory.java:197) at org.springframework.web.util.DefaultUriBuilderFactory.expand(DefaultUriBuilderFactory.java:191) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:679) at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:600) at org.springframework.security.oauth2.provider.token.RemoteTokenServices.postForMap(RemoteTokenServices.java:147) at org.springframework.security.oauth2.provider.token.RemoteTokenServices.loadAuthentication(RemoteTokenServices.java:106) at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager.authenticate(OAuth2AuthenticationManager.java:83) at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:150) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at com.lx.smarthome.securityoauth.permit.PermitAuthenticationFilter.doFilterInternal(PermitAuthenticationFilter.java:122) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) ```

android 5.1 出现java.lang.Throwable: setStateLocked 问题

详细内容如下: AccessibilityManager: setStateLocked: wasEnabled = false, mIsEnabled = false, wasTouchExplorationEnabled = false, mIsTouchExplorationEnabled = false, wasHighTextContrastEnabled = false, mIsHighTextContrastEnabled = false ![图片说明](https://img-ask.csdn.net/upload/201904/08/1554691412_824167.jpg) 报错行指向我的 setContentView(R.layout.login_activity); 页面没有使用悬浮窗 使用不影响不会出现闪退等问题,只是想知道这个是什么

Android通过PHP文件连接到数据库E / Buffer错误:转换结果时出错java.lang.NullPointerException:lock == null

<div class="post-text" itemprop="text"> <p>I am trying to develop a museum search app and try to list my php JSON results in a listView but i can not access my JSON results from Android, i will submit my code and the error messages i get:</p> <p>DisplaySearchResultsActivity.java</p> <pre><code>package com.cloudlionheart.museumsearchapplication; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; public class DisplaySearchResultsActivity extends ListActivity { // Progress Dialog private ProgressDialog pDialog; // Creating JSON Parser object JSONParser jParser = new JSONParser(); ArrayList&lt;HashMap&lt;String, String&gt;&gt; museumItemsList; // url to get all products list private static String url_search_results = "http://192.168.56.1/android_connect/get_all_products.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_MUSEUM_ITEMS = "museum_items"; private static final String TAG_MUSEUM_ITEM_ID = "museum_item_id"; private static final String TAG_MUSEUM_ITEM_NAME = "museum_item_name"; private static final String TAG_MUSEUM_ITEM_ARTIST = "museum_item_artist"; private static final String TAG_MUSEUM_ITEM_HISTORICAL_PERIOD = "museum_item_historic_period"; private static final String TAG_MUSEUM_ITEM_LOCATION = "museum_item_location"; private static final String TAG_MUSEUM_ITEM_IMAGE = "museum_list_image"; // products JSONArray JSONArray museumItems = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_search_resaults); // Hashmap for ListView museumItemsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); // Loading products in Background Thread new LoadAllProducts().execute(); // Get listview ListView lv = getListView(); } /** * Background Async Task to Load all product by making HTTP Request */ class LoadAllProducts extends AsyncTask&lt;String, String, String&gt; { /** * Before starting background thread Show Progress Dialog */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(DisplaySearchResultsActivity.this); pDialog.setMessage("Loading Museum Items. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * getting All products from url */ protected String doInBackground(String... args) { // Building Parameters List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url_search_results, "GET", params); // Check your log cat for JSON reponse Log.d("All Museum Items: ", json.toString()); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); if (success == 1) { // products found // Getting Array of Products museumItems = json.getJSONArray(TAG_MUSEUM_ITEMS); // looping through All Products for (int i = 0; i &lt; museumItems.length(); i++) { JSONObject c = museumItems.getJSONObject(i); // Storing each json item in variable String item_id = c.getString(TAG_MUSEUM_ITEM_ID); String item_name = c.getString(TAG_MUSEUM_ITEM_NAME); String item_artist = c.getString(TAG_MUSEUM_ITEM_ARTIST); String item_historic_period = c.getString(TAG_MUSEUM_ITEM_HISTORICAL_PERIOD); String item_location = c.getString(TAG_MUSEUM_ITEM_LOCATION); String list_image = c.getString(TAG_MUSEUM_ITEM_IMAGE); // creating new HashMap HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); // adding each child node to HashMap key =&gt; value map.put(TAG_MUSEUM_ITEM_ID, item_id); map.put(TAG_MUSEUM_ITEM_NAME, item_name); map.put(TAG_MUSEUM_ITEM_ARTIST, item_artist); map.put(TAG_MUSEUM_ITEM_HISTORICAL_PERIOD, item_historic_period); map.put(TAG_MUSEUM_ITEM_LOCATION, item_location); map.put(TAG_MUSEUM_ITEM_IMAGE, list_image); // adding HashList to ArrayList museumItemsList.add(map); } } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * * */ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( DisplaySearchResultsActivity.this, museumItemsList, R.layout.list_item, new String[]{TAG_MUSEUM_ITEM_ID, TAG_MUSEUM_ITEM_NAME, TAG_MUSEUM_ITEM_ARTIST, TAG_MUSEUM_ITEM_HISTORICAL_PERIOD, TAG_MUSEUM_ITEM_LOCATION, TAG_MUSEUM_ITEM_IMAGE}, new int[]{R.id.museum_item_id, R.id.museum_item_name, R.id.museum_item_artist, R.id.museum_item_historic_period, R.id.museum_item_location, R.id.museum_list_image}); // updating listview setListAdapter(adapter); } }); } } } </code></pre> <p>JSONParser.java</p> <pre><code>package com.cloudlionheart.museumsearchapplication; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; public class DisplaySearchResultsActivity extends ListActivity { // Progress Dialog private ProgressDialog pDialog; // Creating JSON Parser object JSONParser jParser = new JSONParser(); ArrayList&lt;HashMap&lt;String, String&gt;&gt; museumItemsList; // url to get all products list private static String url_search_results = "http://192.168.56.1/android_connect/get_all_products.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_MUSEUM_ITEMS = "museum_items"; private static final String TAG_MUSEUM_ITEM_ID = "museum_item_id"; private static final String TAG_MUSEUM_ITEM_NAME = "museum_item_name"; private static final String TAG_MUSEUM_ITEM_ARTIST = "museum_item_artist"; private static final String TAG_MUSEUM_ITEM_HISTORICAL_PERIOD = "museum_item_historic_period"; private static final String TAG_MUSEUM_ITEM_LOCATION = "museum_item_location"; private static final String TAG_MUSEUM_ITEM_IMAGE = "museum_list_image"; // products JSONArray JSONArray museumItems = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_search_resaults); // Hashmap for ListView museumItemsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); // Loading products in Background Thread new LoadAllProducts().execute(); // Get listview ListView lv = getListView(); } /** * Background Async Task to Load all product by making HTTP Request */ class LoadAllProducts extends AsyncTask&lt;String, String, String&gt; { /** * Before starting background thread Show Progress Dialog */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(DisplaySearchResultsActivity.this); pDialog.setMessage("Loading Museum Items. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * getting All products from url */ protected String doInBackground(String... args) { // Building Parameters List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url_search_results, "GET", params); // Check your log cat for JSON reponse Log.d("All Museum Items: ", json.toString()); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); if (success == 1) { // products found // Getting Array of Products museumItems = json.getJSONArray(TAG_MUSEUM_ITEMS); // looping through All Products for (int i = 0; i &lt; museumItems.length(); i++) { JSONObject c = museumItems.getJSONObject(i); // Storing each json item in variable String item_id = c.getString(TAG_MUSEUM_ITEM_ID); String item_name = c.getString(TAG_MUSEUM_ITEM_NAME); String item_artist = c.getString(TAG_MUSEUM_ITEM_ARTIST); String item_historic_period = c.getString(TAG_MUSEUM_ITEM_HISTORICAL_PERIOD); String item_location = c.getString(TAG_MUSEUM_ITEM_LOCATION); String list_image = c.getString(TAG_MUSEUM_ITEM_IMAGE); // creating new HashMap HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); // adding each child node to HashMap key =&gt; value map.put(TAG_MUSEUM_ITEM_ID, item_id); map.put(TAG_MUSEUM_ITEM_NAME, item_name); map.put(TAG_MUSEUM_ITEM_ARTIST, item_artist); map.put(TAG_MUSEUM_ITEM_HISTORICAL_PERIOD, item_historic_period); map.put(TAG_MUSEUM_ITEM_LOCATION, item_location); map.put(TAG_MUSEUM_ITEM_IMAGE, list_image); // adding HashList to ArrayList museumItemsList.add(map); } } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * * */ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( DisplaySearchResultsActivity.this, museumItemsList, R.layout.list_item, new String[]{TAG_MUSEUM_ITEM_ID, TAG_MUSEUM_ITEM_NAME, TAG_MUSEUM_ITEM_ARTIST, TAG_MUSEUM_ITEM_HISTORICAL_PERIOD, TAG_MUSEUM_ITEM_LOCATION, TAG_MUSEUM_ITEM_IMAGE}, new int[]{R.id.museum_item_id, R.id.museum_item_name, R.id.museum_item_artist, R.id.museum_item_historic_period, R.id.museum_item_location, R.id.museum_list_image}); // updating listview setListAdapter(adapter); } }); } } } </code></pre> <p>and i get the following errors.</p> <pre><code>05-07 10:27:07.177 1942-1962/com.cloudlionheart.museumsearchapplication E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null 05-07 10:27:07.177 1942-1962/com.cloudlionheart.museumsearchapplication E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of 05-07 10:27:07.181 1942-1962/com.cloudlionheart.museumsearchapplication E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:299) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) at java.util.concurrent.FutureTask.setException(FutureTask.java:219) at java.util.concurrent.FutureTask.run(FutureTask.java:239) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) at java.lang.Thread.run(Thread.java:856) Caused by: java.lang.NullPointerException at com.cloudlionheart.museumsearchapplication.DisplaySearchResultsActivity$LoadAllProducts.doInBackground(DisplaySearchResultsActivity.java:94) at com.cloudlionheart.museumsearchapplication.DisplaySearchResultsActivity$LoadAllProducts.doInBackground(DisplaySearchResultsActivity.java:69) at android.os.AsyncTask$2.call(AsyncTask.java:287) at java.util.concurrent.FutureTask.run(FutureTask.java:234)             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)             at java.lang.Thread.run(Thread.java:856) </code></pre> <p>After hours of search and tries i still can't find the way to make it work</p> </div>

JSON解析器错误java.lang.String无法转换为JSONObject] Array

<div class="post-text" itemprop="text"> <p>Hi guys so my problem is ive developed an app for android that uses json parser to get data from my php webservice and display it into a listview, but when i run the app it shows this:</p> <p>LogCat:</p> <pre><code>E/JSON Parser(1999): Error parsing data [Value Array of type java.lang.String cannot be converted to JSONObject] Array 04-02 13:46:46.982: E/JSON Parser(1079): ( 04-02 13:46:46.982: E/JSON Parser(1079): [id] =&gt; 1 04-02 13:46:46.982: E/JSON Parser(1079): [dt_ini_camp] =&gt; 2012-12-22 04-02 13:46:46.982: E/JSON Parser(1079): [dt_fim_camp] =&gt; 2012-12-24 04-02 13:46:46.982: E/JSON Parser(1079): [descricao] =&gt; Apoios comunit?rios 04-02 13:46:46.982: E/JSON Parser(1079): [qtd] =&gt; 4762.000 04-02 13:46:46.982: E/JSON Parser(1079): ) 04-02 13:46:46.982: E/JSON Parser(1079): Array 04-02 13:46:46.982: E/JSON Parser(1079): ( 04-02 13:46:46.982: E/JSON Parser(1079): [id] =&gt; 2 04-02 13:46:46.982: E/JSON Parser(1079): [dt_ini_camp] =&gt; 2012-10-08 04-02 13:46:46.982: E/JSON Parser(1079): [dt_fim_camp] =&gt; 2012-10-10 04-02 13:46:46.982: E/JSON Parser(1079): [descricao] =&gt; Outras Campanhas 04-02 13:46:46.982: E/JSON Parser(1079): [qtd] =&gt; 3560.000 04-02 13:46:46.982: E/JSON Parser(1079): ) </code></pre> <p>My code:</p> <p>Activity with list view and invokes json parser:</p> <pre><code>public class AllProductsActivity extends ListActivity { // Progress Dialog private ProgressDialog pDialog; // Creating JSON Parser object JSONParser jParser = new JSONParser(); ArrayList&lt;HashMap&lt;String, String&gt;&gt; productsList; // url to get all products list private static String url_all_products = "http://10.0.2.2/webprojecto4/index_pesagem.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_PRODUCTS = "cab_doc"; private static final String TAG_ID = "id"; private static final String TAG_NAME = "descricao"; private static final String TAG_DATA = "dt_ini_camp"; private static final String TAG_DATA2 = "dt_fim_camp"; private static final String TAG_QTD = "qtd"; // products JSONArray JSONArray products = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.all_products); // Hashmap for ListView productsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); // Loading products in Background Thread new LoadAllProducts().execute(); // Get listview ListView lv = getListView(); // on seleting single product // launching Edit Product Screen // on seleting single product // launching Edit Product Screen lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { // getting values from selected ListItem String id2 = ((TextView) view.findViewById(R.id.id)).getText() .toString(); // Starting new intent Intent in = new Intent(getApplicationContext(), EditProductActivity.class); // sending pid to next activity in.putExtra(TAG_ID, id); // starting new activity and expecting some response back startActivityForResult(in, 100); } }); } // Response from Edit Product Activity @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // if result code 100 if (resultCode == 100) { // if result code 100 is received // means user edited/deleted product // reload this screen again Intent intent = getIntent(); finish(); startActivity(intent); } } /** * Background Async Task to Load all product by making HTTP Request * */ class LoadAllProducts extends AsyncTask&lt;String, String, String&gt; { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(AllProductsActivity.this); pDialog.setMessage("Loading products. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * getting All products from url * */ protected String doInBackground(String... args) { // Building Parameters List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params); // Check your log cat for JSON reponse Log.d("All Products: ", json.toString()); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); if (success == 1) { // products found // Getting Array of Products products = json.getJSONArray(TAG_PRODUCTS); // looping through All Products for (int i = 0; i &lt; products.length(); i++) { JSONObject c = products.getJSONObject(i); // Storing each json item in variable String id = c.getString(TAG_ID); String name = c.getString(TAG_NAME); String data = c.getString(TAG_DATA); String data2 = c.getString(TAG_DATA2); String qtd = c.getString(TAG_QTD); // creating new HashMap HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); // adding each child node to HashMap key =&gt; value map.put(TAG_ID, id); map.put(TAG_NAME, name); map.put(TAG_DATA, data); map.put(TAG_DATA2, data2); map.put(TAG_QTD, qtd); // adding HashList to ArrayList productsList.add(map); } } else { // no products found // Launch Add New product Activity Intent i = new Intent(getApplicationContext(), NewProductActivity.class); // Closing all previous activities i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( AllProductsActivity.this, productsList, R.layout.list_item, new String[] { TAG_ID, TAG_NAME, TAG_DATA, TAG_DATA2, TAG_QTD}, new int[] { R.id.id, R.id.descricao, R.id.data, R.id.data2, R.id.qtd }); // updating listview setListAdapter(adapter); } }); } } } </code></pre> <p>Json Parser in this i only changed this line BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8); instead of utf-8 it was iso-8859-1 ive searched for this error and based on answers i found it said it would be better utf-8 but it didnt fixed the problem</p> <pre><code>public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List&lt;NameValuePair&gt; params) { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "utf-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + " "); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json); } // return JSON String return jObj; } } </code></pre> <p>And my php service:</p> <pre><code>&lt;?php /* * Following code will list all the products */ // array for JSON response $response = array(); // include db connect class require_once __DIR__ . '/conectaDB.php'; // connecting to db $db = new DB_CONNECT(); // get all products from products table $result = mysql_query("select cd.id, cd.dt_ini_camp, cd.dt_fim_camp, cd.descricao, + (select sum(quantidade) from lin_doc where id_cab_doc = cd.id) as qtd from cab_doc cd where cd.id_tipo_doc = 1") or die(mysql_error()); // check for empty result if (mysql_num_rows($result) &gt; 0) { // looping through all results // products node $response["cab_doc"] = array(); while ($row = mysql_fetch_array($result)) { // temp user array $product = array(); $product["id"] = $row["id"]; $product["dt_ini_camp"] = $row["dt_ini_camp"]; $product["dt_fim_camp"] = $row["dt_fim_camp"]; $product["descricao"] = $row["descricao"]; $product["qtd"] = $row["qtd"]; // push single product into final response array array_push($response["cab_doc"], $product); print_r($product); } // success $response["success"] = 1; // echoing JSON response echo json_encode($response); } else { // no products found $response["success"] = 0; $response["message"] = "No products found"; // echo no users JSON echo json_encode($response); } ?&gt; </code></pre> <p>Please guys i really need help i dont find the problem, the problem i find lol i dont find the answer to my problem xD</p> </div>

线程一直处于RUNNABLE,也没有发现阻塞或是死锁的情况?

我写的是一个频繁访问网络的爬虫,启了20个线程; 但是老实跑了一段时间,线程全部处于RUNNABLE状态了; 网络使用的是httpclient3.1; 我把threaddump给放到下面: ``` "Thread-19" #30 prio=5 os_prio=0 tid=0x0000000059b3d000 nid=0xcb4 runnable [0x000000005ba1e000] java.lang.Thread.State: RUNNABLE at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:150) at java.net.SocketInputStream.read(SocketInputStream.java:121) at java.io.BufferedInputStream.fill(BufferedInputStream.java:246) at java.io.BufferedInputStream.read(BufferedInputStream.java:265) - locked <0x0000000086f05c90> (a java.io.BufferedInputStream) at org.apache.commons.httpclient.HttpParser.readRawLine(HttpParser.java:78) at org.apache.commons.httpclient.HttpParser.readLine(HttpParser.java:106) at org.apache.commons.httpclient.HttpConnection.readLine(HttpConnection.java:1116) at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1973) at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1735) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1098) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) at com.uzons.domain.search.v2.searcher.EBChecker.validate(EBChecker.java:34) at com.uzons.domain.search.v2.taskscheduler.DomainJob.exec(DomainJob.java:28) at com.uzons.domain.search.v2.taskscheduler.DomainScheduler.execute(DomainScheduler.java:110) at com.uzons.domain.search.v2.taskscheduler.DomainScheduler.run(DomainScheduler.java:92) Locked ownable synchronizers: - None ```

通过PHP将信息从MySQL传递到Android - 转换结果时出错java.lang.NullPointerException:lock == null

<div class="post-text" itemprop="text"> <p>I am new to Android and I am trying to make am simple APP the access a server and read a table in a database. I used this example <a href="http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/" rel="nofollow">http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/</a> and tried to make some adaptations.</p> <p>There has been many errors that I was able to solve searching here, but on this case I haven´t been luck so far.</p> <p>As suggest, I did some debbuging and the app stops working when to line 108</p> <pre><code> try{ //Verificando a TAG Sucesso int sucess = json.getInt(TAG_SUCESSO); </code></pre> <p>For the varibles, just befor that, json appears as null.</p> <p>As it seens I am having trouble to get the response from my PHP code (it shows the right array and executed) to the app.</p> <p>Here is the Logcat error</p> <pre><code>12-22 11:50:35.609 1273-1293/br.com.agenciaeisberg.qm E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null 12-22 11:50:35.859 1273-1293/br.com.agenciaeisberg.qm E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of 12-22 11:50:35.859 1273-1293/br.com.agenciaeisberg.qm W/dalvikvm﹕ threadid=12: thread exiting with uncaught exception (group=0xb2a24ba8) 12-22 11:50:36.799 1273-1293/br.com.agenciaeisberg.qm E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1 Process: br.com.agenciaeisberg.qm, PID: 1273 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:841) Caused by: java.lang.NullPointerException at br.com.agenciaeisberg.qm.ListagemHospitaisActivity$LoadListagemHospitais.doInBackground(ListagemHospitaisActivity.java:104) at br.com.agenciaeisberg.qm.ListagemHospitaisActivity$LoadListagemHospitais.doInBackground(ListagemHospitaisActivity.java:76) at android.os.AsyncTask$2.call(AsyncTask.java:288) at java.util.concurrent.FutureTask.run(FutureTask.java:237)             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)             at java.lang.Thread.run(Thread.java:841) 12-22 11:50:38.039 1273-1273/br.com.agenciaeisberg.qm W/EGL_emulation﹕ eglSurfaceAttrib not implemented 12-22 11:50:39.259 1273-1273/br.com.agenciaeisberg.qm E/WindowManager﹕ android.view.WindowLeaked: Activity br.com.agenciaeisberg.qm.ListagemHospitaisActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b2ce6d30 V.E..... R......D 0,0-320,96} that was originally added here at android.view.ViewRootImpl.&lt;init&gt;(ViewRootImpl.java:348) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) at android.app.Dialog.show(Dialog.java:286) at br.com.agenciaeisberg.qm.ListagemHospitaisActivity$LoadListagemHospitais.onPreExecute(ListagemHospitaisActivity.java:88) at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587) at android.os.AsyncTask.execute(AsyncTask.java:535) at br.com.agenciaeisberg.qm.ListagemHospitaisActivity.onCreate(ListagemHospitaisActivity.java:59) at android.app.Activity.performCreate(Activity.java:5231) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) at android.app.ActivityThread.access$800(ActivityThread.java:135) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>Here is the Activity</p> <pre><code>package br.com.agenciaeisberg.qm; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; public class ListagemHospitaisActivity extends ListActivity { // Progress Dialog private ProgressDialog pDialog; // Creating JSON Parser object JSONParser jParser = new JSONParser(); ArrayList&lt;HashMap&lt;String, String&gt;&gt; ListaHospitais; //url para lista hospitais private static String url_lista_hospitais = "http://127.0.0.1/QM/lista_hospitais.php"; //JSON Node names private static final String TAG_HOSPITAIS = "hospitais"; private static final String TAG_PID = "pid"; private static final String TAG_NOME = "nome"; private static final String TAG_SUCESSO = "sucesso"; //private static final String TAG_LOTACAO = "lotacao"; //private static final String TAG_DATA_LOTACAO = "data_lotacao"; //hospitais JSONARRAY JSONArray hospitais = null; @Override public void onCreate (Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.lista_hospitais); //Hashmap for ListView ListaHospitais = new ArrayList&lt;HashMap&lt;String,String&gt;&gt;(); // Carregando hospitais no backgroung new LoadListagemHospitais().execute(); // Get ListView //ListView lv = getListView(); //Selecionando um Hospital //Executa atividade Hospital //Criar código depois -&gt; pesquisar linhas abaixo // on seleting single product // launching Edit Product Screen } /** * Background Async Task para carregar todos os hospitais através de um HTTP Request */ class LoadListagemHospitais extends AsyncTask &lt;String, String, String&gt;{ /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute(){ super.onPreExecute(); pDialog = new ProgressDialog(ListagemHospitaisActivity.this); pDialog.setMessage("Aguarde, carregando Hospitais"); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * Buscando os hospitais do URL * */ protected String doInBackground (String... args) { //Criação dos parâmetros List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); // Buscando o string JSON do URL JSONObject json = jParser.makeHttpRequest(url_lista_hospitais,"GET", params); // Check your log cat for JSON reponse Log.d("Listagem Hospitais: ", json.toString()); try{ //Verificando a TAG Sucesso int sucess = json.getInt(TAG_SUCESSO); if (sucess == 1){ //existe hospital cadastrado // Buscando Array dos hospitais hospitais = json.getJSONArray(TAG_HOSPITAIS); //loop por todos os Hospitais for (int i = 0; i &lt; hospitais.length(); i++) { JSONObject c = hospitais.getJSONObject(i); // Armazenando as variáveis String id = c.getString(TAG_PID); String nome = c.getString(TAG_NOME); // creando novo HashMap HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); // adicionando cada child node ao HashMap . key =&gt; value map.put(TAG_PID, id); map.put(TAG_NOME, nome); // adicionando HashList à ArrayList ListaHospitais.add(map); } }else{ // no products found // Launch Add New product Activity Intent i = new Intent(getApplicationContext(), MainActivity.class); // Closing all previous activities i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); } }catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // Dismiss a caixa de dialogo depois de buscar todos os items pDialog.dismiss(); // atualizando UI from Background Thread runOnUiThread(new Runnable() { public void run() { /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( ListagemHospitaisActivity.this, ListaHospitais, R.layout.lista_hospitais, new String[] { TAG_PID, TAG_NOME}, new int[] { R.id.pid, R.id.nome }); // updating listview setListAdapter(adapter); } }); } } } </code></pre> <p>Here is the JSONParser Class</p> <pre><code>package br.com.agenciaeisberg.qm; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List&lt;NameValuePair&gt; params) { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + " "); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } </code></pre> <p>Here is the php Code</p> <pre><code>&lt;?php /* * O código a seguir lista todos os hospitais */ //array para Resposta JSON $response = array(); require_once 'geral.inc.php'; // connecting to db $con = mysqli_connect($hostname, $username, $senha, $banco); // Listar todos os Hospitais $result = mysqli_query($con, 'SELECT * FROM hospitais'); $response['hospitais'] = array(); while ($row = mysqli_fetch_array($result)){ //array temporário $hospital = array (); $hospital['pid'] = $row['PID']; $hospital['nome'] = $row['NomeHospital']; $hospital['lotacao'] = $row['ultima_lotacao']; $hospital['data_lotacao'] = $row['d_h_ultima_lotacao']; // Exibe o resultado um a um da array array_push($response["hospitais"], $hospital); } $response["successo"] = 1; // echoing JSON response echo json_encode($response); ?&gt; </code></pre> </div>

急求。。。。。看下java的dump文件,会这样

2015-03-18 22:38:54 Full thread dump Java HotSpot(TM) Client VM (20.1-b02 mixed mode, sharing): "Attach Listener" daemon prio=10 tid=0x089f1c00 nid=0x1df1 waiting on condition [0x00000000] java.lang.Thread.State: RUNNABLE Locked ownable synchronizers: - None "DestroyJavaVM" prio=10 tid=0x0806f400 nid=0x1297 waiting on condition [0x00000000] java.lang.Thread.State: RUNNABLE Locked ownable synchronizers: - None "pool-1-thread-1" prio=10 tid=0x08a70c00 nid=0x1341 waiting on condition [0xb4806000] java.lang.Thread.State: WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for <0x7a13b978> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject) at java.util.concurrent.locks.LockSupport.park(LockSupport.java:158) at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:1987) at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:399) at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:947) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907) at java.lang.Thread.run(Thread.java:662) Locked ownable synchronizers: - None "Low Memory Detector" daemon prio=10 tid=0x080b3800 nid=0x129d runnable [0x00000000] java.lang.Thread.State: RUNNABLE Locked ownable synchronizers: - None "C1 CompilerThread0" daemon prio=10 tid=0x080a8000 nid=0x129c waiting on condition [0x00000000] java.lang.Thread.State: RUNNABLE Locked ownable synchronizers: - None "Signal Dispatcher" daemon prio=10 tid=0x080a6800 nid=0x129b runnable [0x00000000] java.lang.Thread.State: RUNNABLE Locked ownable synchronizers: - None "Finalizer" daemon prio=10 tid=0x0809e800 nid=0x129a in Object.wait() [0xb4ed9000] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait(Native Method) - waiting on <0x7a040258> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118) - locked <0x7a040258> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134) at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159) Locked ownable synchronizers: - None "Reference Handler" daemon prio=10 tid=0x0809d400 nid=0x1299 in Object.wait() [0xb4f2b000] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait(Native Method) - waiting on <0x7a0402e8> (a java.lang.ref.Reference$Lock) at java.lang.Object.wait(Object.java:485) at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:116) - locked <0x7a0402e8> (a java.lang.ref.Reference$Lock) Locked ownable synchronizers: - None "VM Thread" prio=10 tid=0x08092c00 nid=0x1298 runnable "VM Periodic Task Thread" prio=10 tid=0x080b5800 nid=0x129e waiting on condition JNI global references: 1109 我使用了Executors.newFixedThreadPool线程池来执行任务,,,主进程退出不了。 为什么啊???

错误:org.json.JSONException:java.lang.String类型的值<br无法转换为JSONObject

<div class="post-text" itemprop="text"> <p>I know I have seen all similar questions on SO. I tried to solve this error but I failed. I tried almost everything but does not get solution.</p> <p>My code is as follows:-</p> <pre><code>public class Tab2 extends Fragment { private static String TAG = Tab2.class.getSimpleName(); private EditText editText1,editText2,editText3; private Button button; private String name,email,password; private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutPassword; private ProgressDialog pDialog; private SessionManager session; private database db; static InputStream is = null; static JSONObject jObj = null; static String json = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tab2,container,false); pDialog = new ProgressDialog(getActivity()); pDialog.setCancelable(false); // Session manager session = new SessionManager(getActivity()); // SQLite database handler db = new database(getActivity()); // Check if user is already logged in or not if (session.isLoggedIn()) { // User is already logged in. Take him to main activity Intent intent = new Intent(getActivity(),MainActivity.class); startActivity(intent); } editText1 = (EditText)view.findViewById(R.id.name); editText2 = (EditText)view.findViewById(R.id.email); editText3 = (EditText)view.findViewById(R.id.password); inputLayoutEmail = (TextInputLayout)view. findViewById(R.id.view1); inputLayoutPassword = (TextInputLayout)view. findViewById(R.id.view2); inputLayoutName = (TextInputLayout)view. findViewById(R.id.view3); button = (Button)view.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view1) { name = editText1.getText().toString().trim(); email = editText2.getText().toString().trim(); password = editText3.getText().toString().trim(); if (!validateName() || !validateEmail() || !validatePassword() ) { Log.d(TAG, "Successfull"); return; } try { new Thread(new Runnable() { @Override public void run() { registerUser(name, email, password); } }).start(); }catch (NullPointerException e){ e.printStackTrace(); } Toast.makeText(getActivity(), "Account Created Successfully!", Toast.LENGTH_SHORT).show(); Intent i = new Intent(getActivity(), MainActivity.class); startActivity(i); } }); return view; } public boolean validateName(){ if(name.isEmpty() ) { inputLayoutName.setError(getString(R.string.error_name1)); return false; } else if(name.length()&lt;3){ inputLayoutName.setError(getString(R.string.error_name2)); return false; } else inputLayoutName.setErrorEnabled(false); return true; } public boolean validateEmail(){ if(email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){ inputLayoutEmail.setError(getString(R.string.error_email)); return false; } else inputLayoutEmail.setErrorEnabled(false); return true; } public boolean validatePassword(){ if(password.isEmpty() ){ inputLayoutPassword.setError(getString(R.string.error_password1)); return false; } else if(password.length()&lt;4){ inputLayoutPassword.setError(getString(R.string.error_password2)); return false; } else inputLayoutPassword.setErrorEnabled(false); return true; } public void registerUser(final String name, final String email, final String password){ String req = "req_request"; pDialog.setMessage("Registering ..."); showDialog(); RequestQueue requestQueue = Volley.newRequestQueue(getActivity()); StringRequest strReq = new StringRequest(Request.Method.POST, appConfig.url_sign, new Response.Listener&lt;String&gt;(){ @Override public void onResponse(String response) { try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); Log.d(TAG,name + " " + email + " " + password ); if (!error) { String uid = jObj.getString("uid"); JSONObject user = jObj.getJSONObject("user"); String name = user.getString("name"); String email= user.getString("email"); String created_at = user.getString("created_at"); db.addUser(name, email, uid, created_at); Toast.makeText(getActivity(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show(); // Launch login activity Intent i = new Intent( getActivity(), Login.class); startActivity(i); } else { String errorMsg = jObj.getString("error_msg"); Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { NetworkResponse networkResponse = error.networkResponse; if (networkResponse != null) { Log.e("Volley", "Error. HTTP Status Code:"+networkResponse.statusCode); } if (error instanceof TimeoutError) { Log.e("Volley", "TimeoutError"); }else if(error instanceof NoConnectionError){ Log.e("Volley", "NoConnectionError"); } else if (error instanceof AuthFailureError) { Log.e("Volley", "AuthFailureError"); } else if (error instanceof ServerError) { Log.e("Volley", "ServerError"); } else if (error instanceof NetworkError) { Log.e("Volley", "NetworkError"); } else if (error instanceof ParseError) { Log.e("Volley", "ParseError"); } //Log.e(TAG, "Registration Error: " + error.getMessage()); // Toast.makeText(getActivity(), // error.getMessage(), Toast.LENGTH_LONG).show(); // hideDialog(); } }) { @Override protected Map&lt;String, String&gt; getParams() { // Posting params to register url Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;(); params.put("name", name); params.put("email", email); params.put("password", password); return params; } }; int socketTimeout = 10000;//30 seconds - change to what you want RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); strReq.setRetryPolicy(policy); requestQueue.add(strReq); } private void showDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hideDialog() { if (pDialog.isShowing()) pDialog.dismiss(); } } </code></pre> <p>This is my php file</p> <pre><code>&lt;?php $response = array(); if (isset($_POST['name']) &amp;&amp; isset($_POST['email']) &amp;&amp; isset ($_POST['password'] )) { $name = $_POST['name']; $email = $_POST['email']; $password = $_POST['password']; require_once __DIR__ . '/db_connection.php'; $db = new DB_CONNECT(); $result = mysql_query("Insert into words(name,email,password) values('$name','$email','$password')"); if ($result) { $response["success"] = 1; $response["message"] = "Registration successfully."; echo json_encode($response); } else { $response["success"] = 0; $response["message"] = "Oops! An error occurred."; echo json_encode($response); } } else { $response["success"] = 0; $response["message"] = "Required field(s) is missing"; echo json_encode($response); } ?&gt; </code></pre> <p>My JSON response is:-</p> <pre><code>{"success":0,"message":"Required field(s) is missing"} </code></pre> <p>Can you identify the error please tell me.</p> </div>

locked (a java.util.zip.ZStreamRef) 锁不释放,cpu满负载

"llcs-117" prio=10 tid=0x00007f716c15f000 nid=0x267f runnable [0x00007f715338d000] java.lang.Thread.State: RUNNABLE at java.util.zip.Inflater.inflateBytes(Native Method) at java.util.zip.Inflater.inflate(Inflater.java:259) - locked <0x0000000741d9e308> (a java.util.zip.ZStreamRef) at java.util.zip.Inflater.inflate(Inflater.java:280) 都是类似如此的线程,最大值设置了200个,有一半以上的线程是这个状态

JAVA项目运行cup占用率100%,使用explorer工具查询java.exe下的线程占用率过高(如图),谁帮助分析下?

![图片说明](https://img-ask.csdn.net/upload/201906/26/1561532013_676978.jpg) 定位在如下的的日志上,请帮助分析。谢谢! 2019-06-26 14:34:07 "XNIO-1 Accept" #19 daemon prio=5 os_prio=0 tid=0x0000000058231000 nid=0x3ec runnable [0x000000005badf000] java.lang.Thread.State: RUNNABLE at java.lang.Object.notifyAll(Native Method) at sun.nio.ch.WindowsSelectorImpl$StartLock.startThreads(WindowsSelectorImpl.java:189) - locked <0x00000000d3d825c0> (a sun.nio.ch.WindowsSelectorImpl$StartLock) at sun.nio.ch.WindowsSelectorImpl$StartLock.access$300(WindowsSelectorImpl.java:181) at sun.nio.ch.WindowsSelectorImpl.doSelect(WindowsSelectorImpl.java:153) at sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:86) - locked <0x00000000d3d71eb8> (a sun.nio.ch.Util$2) - locked <0x00000000d3d71ec8> (a java.util.Collections$UnmodifiableSet) - locked <0x00000000d3d71e38> (a sun.nio.ch.WindowsSelectorImpl) at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:97) at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:101) at org.xnio.nio.WorkerThread.run(WorkerThread.java:511) Locked ownable synchronizers: - None "XNIO-1 I/O-1" #18 daemon prio=5 os_prio=0 tid=0x0000000054092800 nid=0xf54 runnable [0x000000005b85f000] java.lang.Thread.State: RUNNABLE at sun.nio.ch.WindowsSelectorImpl$SubSelector.poll0(Native Method) at sun.nio.ch.WindowsSelectorImpl$SubSelector.poll(WindowsSelectorImpl.java:296) at sun.nio.ch.WindowsSelectorImpl$SubSelector.access$400(WindowsSelectorImpl.java:278) at sun.nio.ch.WindowsSelectorImpl.doSelect(WindowsSelectorImpl.java:159) at sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:86) - locked <0x00000000d3d751e0> (a sun.nio.ch.Util$2) - locked <0x00000000d3d751f0> (a java.util.Collections$UnmodifiableSet) - locked <0x00000000d3d75160> (a sun.nio.ch.WindowsSelectorImpl) at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:97) at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:101) at org.xnio.nio.WorkerThread.run(WorkerThread.java:511) Locked ownable synchronizers: - None

编写的java登录页面一运行就报这样的错误

HTTP Status 500 – Internal Server Error Type Exception Report Message Servlet execution threw an exception Description The server encountered an unexpected condition that prevented it from fulfilling the request. Exception javax.servlet.ServletException: Servlet execution threw an exception org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) Root Cause java.lang.NoClassDefFoundError: com/itheima/Utils/DruidUtils com.itheima.Dao.loginDao.findUserByNameAndPwd(loginDao.java:13) com.itheima.service.LoginService.login(LoginService.java:10) com.itheima.web.servlet.LoginServlet.doPost(LoginServlet.java:39) com.itheima.web.servlet.LoginServlet.doGet(LoginServlet.java:55) javax.servlet.http.HttpServlet.service(HttpServlet.java:635) javax.servlet.http.HttpServlet.service(HttpServlet.java:742) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) Root Cause java.lang.ClassNotFoundException: com.itheima.Utils.DruidUtils org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1291) org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119) com.itheima.Dao.loginDao.findUserByNameAndPwd(loginDao.java:13) com.itheima.service.LoginService.login(LoginService.java:10) com.itheima.web.servlet.LoginServlet.doPost(LoginServlet.java:39) com.itheima.web.servlet.LoginServlet.doGet(LoginServlet.java:55) javax.servlet.http.HttpServlet.service(HttpServlet.java:635) javax.servlet.http.HttpServlet.service(HttpServlet.java:742) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) Note The full stack trace of the root cause is available in the server logs. 运行报错找不到原因

jetty线程出现堆积,处理不过来现象,求分析和解决半封闭

"jetty-server-127" #173 prio=5 os_prio=0 tid=0x00007f4f4005a000 nid=0xf580 waiting on condition [0x00007f4e301c0000] java.lang.Thread.State: WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for <0x00000000ab59cda0> (a java.util.concurrent.SynchronousQueue$TransferStack) at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175) at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:458) at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362) at java.util.concurrent.SynchronousQueue.take(SynchronousQueue.java:924) at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) at com.kugou.thread.Threads$RunnableThread.run(Threads.java:244) Locked ownable synchronizers: - None "jetty-server-126" #172 prio=5 os_prio=0 tid=0x00007f4f38003000 nid=0xf57f waiting on condition [0x00007f4e302c1000] java.lang.Thread.State: WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for <0x00000000ab59cda0> (a java.util.concurrent.SynchronousQueue$TransferStack) at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175) at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:458) at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362) at java.util.concurrent.SynchronousQueue.take(SynchronousQueue.java:924) at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) at com.kugou.thread.Threads$RunnableThread.run(Threads.java:244) Locked ownable synchronizers: - None "jetty-server-125" #171 prio=5 os_prio=0 tid=0x00007f4f3403d000 nid=0xf57e waiting on condition [0x00007f4e303c2000] java.lang.Thread.State: WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for <0x00000000ab59cda0> (a java.util.concurrent.SynchronousQueue$TransferStack) at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175) at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:458) at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362) at java.util.concurrent.SynchronousQueue.take(SynchronousQueue.java:924) at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) at com.kugou.thread.Threads$RunnableThread.run(Threads.java:244) Locked ownable synchronizers: - None vi -c 1 mynew.log 2.lang.Thread.State: WAITING (parking)017-10-24 20:57:01 Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.40-b25 mixed mode): "Attach Listener" #26239 daemon prio=9 os_prio=0 tid=0x00007f4fbc001000 nid=0xeb30 waiting on condition [0x0000000000000000] java.lang.Thread.State: RUNNABLE Locked ownable synchronizers: - None "jetty-server-127" #173 prio=5 os_prio=0 tid=0x00007f4f4005a000 nid=0xf580 waiting on condition [0x00007f4e301c0000] java.lang.Thread.State: WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for <0x00000000ab59cda0> (a java.util.concurrent.SynchronousQueue$TransferStack) at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175) at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:458) at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362) at java.util.concurrent.SynchronousQueue.take(SynchronousQueue.java:924) at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) at com.kugou.thread.Threads$RunnableThread.run(Threads.java:244) Locked ownable synchronizers: - None "jetty-server-126" #172 prio=5 os_prio=0 tid=0x00007f4f38003000 nid=0xf57f waiting on condition [0x00007f4e302c1000] java.lang.Thread.State: WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for <0x00000000ab59cda0> (a java.util.concurrent.SynchronousQueue$TransferStack) at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175) at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:458) at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362) at java.util.concurrent.SynchronousQueue.take(SynchronousQueue.java:924) at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) at com.kugou.thread.Threads$RunnableThread.run(Threads.java:244) Locked ownable synchronizers: - None "jetty-server-125" #171 prio=5 os_prio=0 tid=0x00007f4f3403d000 nid=0xf57e waiting on condition [0x00007f4e303c2000] java.lang.Thread.State: WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for <0x00000000ab59cda0> (a java.util.concurrent.SynchronousQueue$TransferStack) at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175) at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:458) at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362) at java.util.concurrent.SynchronousQueue.take(SynchronousQueue.java:924) at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) at com.kugou.thread.Threads$RunnableThread.run(Threads.java:244) Locked ownable synchronizers: - None

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

点沙成金:英特尔芯片制造全过程揭密

“亚马逊丛林里的蝴蝶扇动几下翅膀就可能引起两周后美国德州的一次飓风……” 这句人人皆知的话最初用来描述非线性系统中微小参数的变化所引起的系统极大变化。 而在更长的时间尺度内,我们所生活的这个世界就是这样一个异常复杂的非线性系统…… 水泥、穹顶、透视——关于时间与技艺的蝴蝶效应 公元前3000年,古埃及人将尼罗河中挖出的泥浆与纳特龙盐湖中的矿物盐混合,再掺入煅烧石灰石制成的石灰,由此得来了人...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

我说我不会算法,阿里把我挂了。

不说了,字节跳动也反手把我挂了。

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

你打算用Java 8一辈子都不打算升级到Java 14,真香

我们程序员应该抱着尝鲜、猎奇的心态,否则就容易固步自封,技术停滞不前。

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

一文带你入门Java Stream流,太强了

两个星期以前,就有读者强烈要求我写一篇 Java Stream 流的文章,我说市面上不是已经有很多了吗,结果你猜他怎么说:“就想看你写的啊!”你看你看,多么苍白的喜欢啊。那就“勉为其难”写一篇吧,嘻嘻。 单从“Stream”这个单词上来看,它似乎和 java.io 包下的 InputStream 和 OutputStream 有些关系。实际上呢,没毛关系。Java 8 新增的 Stream 是为...

立即提问
相关内容推荐