{"id":14028,"date":"2022-10-06T06:51:16","date_gmt":"2022-10-06T01:21:16","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/"},"modified":"2022-10-06T06:51:16","modified_gmt":"2022-10-06T01:21:16","slug":"solved-returning-values-from-thread","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/","title":{"rendered":"[Solved] Returning values from thread"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-45020161\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"45020161\" data-parentid=\"44973236\" data-score=\"1\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>Your code, in general, seems pretty solid, but there are several problems.<br \/>\nThe task you created does the trick, and the progress bar will work, but it uses a thread so returning that the tests are complete without confirming the progress of the thread is wrong. Because the tests are in a thread and the method returns a value without being dependent on it, the value is returned before the tests are done.<br \/>\nWhen calling <code>thread.start()<\/code> the thread starts execution seperatly from your current thread, meaning that your code continues to execute as usual even if the thread was not done.<\/p>\n<p>You have 2 possible options: keep the thread, or don&#8217;t. If you don&#8217;t keep the thread, that means that the tests are executed in the method which causes the javaFX event that called it to wait for the tests to finish. This is a bad idea because now the javaFX thread is stuck and the window can&#8217;t handle any other events (basically, iresponsive).<\/p>\n<p>A good option is to keep the thread, only that at the end of the thread you could show a dialog indicating whether the tests were complete or not. To do that you can use <code>Platform.runLater(runnable)<\/code> and pass it a <code>Runnable<\/code> object which shows the dialog:<\/p>\n<pre><code>Platform.runLater(()-&gt;{\n   \/\/show dialog\n});\n<\/code><\/pre>\n<p>It is required because you can&#8217;t show a dialog while not in the javaFX thread. This allows you to run something in the javaFX thread.<\/p>\n<p>Another issue is the fact that you&#8217;re accessing the files outside of your thread. Meaning that at the same time the thread runs your test, you attempt to access the files and write to them. Instead of doing that, you should either write to the file in the thread or before it is started. <\/p>\n<p>To summerize it all, you should use your thread to execute the tests and show the dialogs which indicate whether or not the tests were completed. Writing to your test file should not be done while the thread is still executing tests, but rather after the thread was finished, so you can do it at the end of the task.<\/p>\n<pre><code>public void runTests(){\n    if(testsRunning) return;\n\n    testsRunning = true;\n\n    final Task&lt;Void&gt; task = new Task&lt;Void&gt;() {\n        @Override\n        protected Void call() throws Exception {\n            FileInputStream fis = null;\n            File testDataFile = null;\n            try {\n                fis = new FileInputStream(selectedTestDataFile);\n            } catch (FileNotFoundException e) {\n                displayResponse(\"File Input Stream Error: File Not Found\");\n            }\n\n            \/\/ Finds the workbook instance for XLSX file\n            XSSFWorkbook myWorkBook = null;\n            try {\n                myWorkBook = new XSSFWorkbook(fis);\n            } catch (IOException e) {\n                displayResponse(\"XSSFWorkbook I\/O Error\");\n            }\n\n            \/\/ displayResponse(first sheet from the XLSX workbook\n            XSSFSheet mySheet = myWorkBook.getSheetAt(0);\n\n            int totalWids = mySheet.getLastRowNum();\n\n            for (int rowIndex = 1; rowIndex &lt;= totalWids; rowIndex++) {\n                updateProgress(rowIndex, totalWids);\n                Row row = mySheet.getRow(rowIndex);\n                if (row != null) {\n                    String data = \"\");\n\n                    Cell cellData = row.getCell(2);\n\n                    if (cellData != null) {\n                        data = cellWid.getStringCellValue();\n                        boolean testresult = runTest(data);\n                        System.out.println(rowIndex + \". data = \" + data + \", testresult = \" + testresult);\n                    }\n                }\n            }\n\n            \/* xlsx read *\/\n            FileOutputStream fos = null;\n            try {\n                fos = new FileOutputStream(selectedTestDataFile);\n            } catch (FileNotFoundException e) {\n                try {\n                    myWorkBook.close();\n                } catch (IOException e1) {\n                    displayResponse(\"Error: Please Close Workbook\");\n                }\n                displayResponse(\"Error: File Not Found\");\n            }\n            try {\n                myWorkBook.write(fos);\n            } catch (IOException e) {\n                try {\n                    myWorkBook.close();\n                } catch (IOException e1) {\n                    displayResponse(\"Error: Please Close Workbook\");\n                }\n                displayResponse(\"Error: Workbook Write\");\n            }\n            try {\n                fos.close();\n            } catch (IOException e) {\n                try {\n                    myWorkBook.close();\n                } catch (IOException e1) {\n                    displayResponse(\"Error: Please Close Workbook\");\n                }\n                displayResponse(\"Error: File Output Stream\");\n            }\n            try {\n                myWorkBook.close();\n            } catch (IOException e) {\n                displayResponse(\"Error: Please Close Workbook\");\n            }\n            try {\n                fis.close();\n            } catch (IOException e) {\n                displayResponse(\"Error: Input file format\");\n            }\n\n            displayResponse(\"Testing Complete!\");\n\n            return null;\n        }\n        private void displayResponse(String testResultMessage){\n            Platform.runLater(()-&gt;{\n                if (testResultMessage.equals(\"Testing Complete!\")) {\n                    Alert alert = DialogUtils.getAlert(\"Info\", \"Information\", testResultMessage, \"info\");\n                    alert.showAndWait();\n\n                } else {\n                    Alert alert = DialogUtils.getAlert(\"Error\", \"Error(s)\", testResultMessage, \"error\");\n                    alert.showAndWait();\n                }\n                testsRunning = false;\n            });\n        }\n    };\n\n    progressBar.progressProperty().bind(task.progressProperty());\n    progressIndicator.progressProperty().bind(task.progressProperty());\n\n    final Thread thread = new Thread(task, \"task-thread\");\n    thread.setDaemon(true);\n    thread.start();\n}\n<\/code><\/pre>\n<p>So this code now does everything test related in the thread and doesn&#8217;t interrupt your window from handling events. There is one problem from this: someone might press the <code>runTests<\/code> button again, while the tests are running. One option is to use a boolean indicating whether the tests are already active and check its value when <code>runTests<\/code> is called which I added and is called <code>testsRunning<\/code>. <code>displayResponse<\/code> is called when the tests where finished (completed or not) and it displayes the response dialog. <\/p>\n<p>Hope I helped, and sorry for the long answer.<\/p>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\"><\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Returning values from thread <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] Your code, in general, seems pretty solid, but there are several problems. The task you created does the trick, and the progress bar will work, but it uses a thread so returning that the tests are complete without confirming the progress of the thread is wrong. Because the tests are in a thread and &#8230; <a title=\"[Solved] Returning values from thread\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/\" aria-label=\"More on [Solved] Returning values from thread\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[323,1489,884,2264],"class_list":["post-14028","post","type-post","status-publish","format-standard","hentry","category-solved","tag-java","tag-javafx","tag-multithreading","tag-task"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] Returning values from thread - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Returning values from thread - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] Your code, in general, seems pretty solid, but there are several problems. The task you created does the trick, and the progress bar will work, but it uses a thread so returning that the tests are complete without confirming the progress of the thread is wrong. Because the tests are in a thread and ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-10-06T01:21:16+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Returning values from thread\",\"datePublished\":\"2022-10-06T01:21:16+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/\"},\"wordCount\":451,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"java\",\"javafx\",\"multithreading\",\"task\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/\",\"name\":\"[Solved] Returning values from thread - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-10-06T01:21:16+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Returning values from thread\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Returning values from thread - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Returning values from thread - JassWeb","og_description":"[ad_1] Your code, in general, seems pretty solid, but there are several problems. The task you created does the trick, and the progress bar will work, but it uses a thread so returning that the tests are complete without confirming the progress of the thread is wrong. Because the tests are in a thread and ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/","og_site_name":"JassWeb","article_published_time":"2022-10-06T01:21:16+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Returning values from thread","datePublished":"2022-10-06T01:21:16+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/"},"wordCount":451,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["java","javafx","multithreading","task"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/","url":"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/","name":"[Solved] Returning values from thread - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-10-06T01:21:16+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-returning-values-from-thread\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Returning values from thread"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/14028","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=14028"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/14028\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=14028"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=14028"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=14028"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}