2016-12-30 75 views
-2

對不起,我的游泳池英語。 我有一個javaFx應用程序需要連接到許多套接字服務器(超過40),這是在Android手機開始。 當連接到服務器時,我建立一個線程來保存長連接,每隔600毫秒服務器將SCREENSHOT(二進制)發送到我的應用程序。 javaFx應用程序不能是服務器。 下面是部分代碼:如何在Socket長連接中保持CPU使用率較低

while (ScreenMonitorService.isConnectionAll()){ 
Future<Image> f = ThreadPoolUtil.getThreadPool().submit(new Callable<Image>() { 
    @Override 
    public Image call() throws Exception { 
     return readImage(inputStream, outputStream); 
    } 
    }); 
Image fxImage = f.get(); 
Platform.runLater(()->{ 
    device.getImageView().setImage(fxImage); 
}); 


//what readImage do 
private synchronized Image readImage(InputStream inputStream, OutputStream outputStream) throws IOException { 
try { 
     Thread.sleep(700);<==== This is the now solution for high cpu performtion , but it doesn't work 
    } catch (InterruptedException e) { 
     logger.error("=====> error", e); 
    } 
    int fileLen = readInt(inputStream); 
    int readLength = fileLen; 
    int tempLength = 0; 
    int n; 
    byte[] bt = new byte[readLength]; 
    ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
    while ((n = inputStream.read(bt,0,readLength)) > 0) { 
     tempLength += n; 
     readLength = tempLength + n > fileLen ? fileLen - tempLength : readLength; 
     bout.write(bt,0,n); 
    } 
    ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); 
    BufferedImage image = ImageIO.read(bin); 
    Image fxImage = SwingFXUtils.toFXImage(image,null); 
    writeInt(outputStream,1); 
    return fxImage; 
} 

我知道這是繁忙的,瓦亭,這使得壞CPU的性能。 我已經使用nio | notify/wait | blockqueue嘗試解決問題,但失敗。 可能有人可以給我一些建議來解決這個問題,謝謝。

回答

0

實際上......你並不是在等待,而sleep也不是你問題的原因。

你真正應該做的是個人資料查看它在哪裏花費大部分時間的代碼。我嫌疑,它實際上是在這兩個電話:

BufferedImage image = ImageIO.read(bin); 
    Image fxImage = SwingFXUtils.toFXImage(image, null); 

換句話說,我懷疑,大多數CPU的在轉換圖像是怎麼回事。如果是這種情況,那麼你需要找出一種辦法來減少圖像處理。

這也可能是一個與GC相關的問題,但分析也會爲此提供證據。


我注意到你在處理它之前緩衝了整個文件。這可能會讓事情變得更慢。你可以通過將InputStream包裝在BufferedInputStream中並將BIS傳遞給ImageIO.read來避免這種情況。但我不認爲字節的雙重處理是主要問題。

+0

我已經剖析了代碼。 – alongsea2

+0

轉換成本約爲200毫秒。 – alongsea2

+0

也感謝您的建議 – alongsea2