====== Java ====== * [[youtube>hcY8cYfAEwU|OSCON Java 2011: Josh Bloch, "Java: The Good, Bad, and Ugly Parts"]] * [[youtube>0zVizaCOhME|Closures For Java -- Google Tech Talks 2007]] * [[https://blog.idrsolutions.com/2014/06/java-performance-tuning-tools/|9 tools to help you with Java Performance Tuning]] * [[habrahabr>263685|Как правильно использовать исключения]] * [[habrahabr>268683|Польза проверяемых исключений весьма сомнительна, а вред очевиден]] * [[github>akullpp/awesome-java|Awesome Java]] -- curated list of awesome Java frameworks, libraries and software * [[habrahabr>266821|Шпаргалки Java программиста 2: Триста пятьдесят самых популярных не мобильных Java opensource проектов на github]] * [[habrahabr>269023|HikariCP — самый быстрый пул соединений на java]] * [[habrahabr>302734|Дайджест интересных событий из мира Java, и вокруг нее #3 (23.05.2016 — 05.06.2016)]] ===== Effective Java ===== * [[youtube>V1vQf4qyMXg|Effective Java - Still Effective After All These Years]] * [[youtube>pi_I7oD_uGI|Google I/O 2008 - Effective Java Reloaded]] is a similar talk * [[habrahabr>278329|Никогда не делайте компараторов на базе вычитания]] ===== Java internals ===== * [[http://www.ibm.com/developerworks/java/library/j-nativememory-linux/|Understanding how the JVM uses native memory on Windows and Linux]] covers the native memory organization principles, virtual memory, GC, JIT, classloaders, reflection, JNI, NIO. * [[http://download.boulder.ibm.com/ibmdl/pub/software/dw/jdk/diagnosis/dw3gbswitch3.pdf|Windows Java address space]] is about how to maximize the IBM Java memory address space on 32-bit Windows systems. * [[http://www.infoq.com/presentations/JVM-Performance-Tuning-twitter|JVM Performance Tuning]] touches the topics: What is the tradeoff among memory, throughput and latency? What is new and old generation heap? What are the different GC implementations and how to tune them? How soft references are GC'ed? * [[habrahabr>148139|Использование разделяемой памяти в Java и off-heap кеширование]] -- рассказывает в том числе, как отображать файлы размером более 2 GB. * [[habrahabr>111897|Сбор интересных вопросов по Java Performance]] * [[habrahabr>143468|Do It Yourself Java Profiling]] * [[habrahabr>195004|Манипуляции с флагами HotSpot JVM на лету посредством прямого доступа к памяти JVM]] * [[stackoverflow>1159087|Inlining in Java]] * [[habrahabr>134102|Размер Java объектов]] * [[habrahabr>142409|Размеры массивов в Java]] * [[habrahabr>124909|Сравнение потребления памяти у разных структур хранения данных]] * [[habrahabr>145145|Строковые коллекции только для чтения: экономим на спичках]] * [[habrahabr>218313|Утечка памяти с ThreadLocal]] * [[youtube>Svc0WtfV63k|Java Runtime: повседневные обязанности виртуальной машины Java]] * [[googlecode>p/caliper/|Caliper]] -- microbenchmarking framework for Java * [[habrahabr>332460|Зачем мне твои неизменяемые коллекции? Они же медленные]] -- тест функионального и императивного подхода на производительность при работе с коллекциями ===== Java Native Interfaces ===== * [[http://gcc.gnu.org/onlinedocs/gcj/About-CNI.html|CNI]] is the alternative to [[wp>Java Native Interface|JNI]] in case you use [[wp>JCG]]. It allows you to write classes in C++ (which can be extended by Java) and call native functions. * [[https://github.com/java-native-access/jna|JNA]] allows to call native functions dynamically at runtime without JNI code generation. The signature for native method is generated from Java interface with automatic mapping for all data types (primitives, strings, structures, unions, arrays, function pointers for callbacks from native code to Java, varargs). * [[googlecode>p/jnaerator/|JNAerator]] -- parses C / C++ & Objective-C headers and generates the corresponding [[http://bridj.googlecode.com/|BridJ]], [[http://jna.dev.java.net/|JNA]] and [[https://rococoa.dev.java.net/|Rococoa]] Java interfaces. * [[habrahabr>222997|Дорог ли native метод? "Секретное" расширение JNI]] -- недокументированная возможность HotSpot JVM 7 для ускоренного вызова простых JNI методов ===== Java code search ===== * [[http://grepcode.com/]] * [[http://www.google.com/codesearch]] ===== Java code quality control ===== * [[http://www.ucdetector.org/|UCDetector]] -- Unnecessary Code Detector Eclipse plugin * [[http://eclipse-cs.sourceforge.net/|Checkstyle]] -- Eclipse plugin for Check stylecode analyzer * [[http://findbugs.sourceforge.net/|FindBugs]] -- Eclipse plugin for static analysis to look for bugs in Java code * [[http://ecobertura.johoop.de/|Cobertura]] -- Eclipse plugin for Cobertura Java code coverage reporting tool * [[http://www.copperykeenclaws.com/notes-on-cobertura-vs-emma-vs-clover/|Java Code Coverage: Cobertura vs. Emma vs Clover]] * [[http://performance.netbeans.org/insane/|Insane]] -- The postmortem memory leak analysis tool * [[http://www.javaworld.com/javaworld/javaqa/2003-12/02-qa-1226-sizeof.html?page=5|Calculation of memory wastes due to character allocation]] ===== [[wp>Reactive programming]] ===== * [[https://spring.io/blog/2016/06/07/notes-on-reactive-programming-part-i-the-reactive-landscape|Notes on Reactive Programming, part 1]], [[https://spring.io/blog/2016/06/13/notes-on-reactive-programming-part-ii-writing-some-code|part 2]], [[https://spring.io/blog/2016/07/20/notes-on-reactive-programming-part-iii-a-simple-http-server-application|part 3]] ({{reactive_programming.docx|local copy}}). * [[https://gist.github.com/staltz/868e7e9bc2a7b8c1f754|The introduction to Reactive Programming you've been missing]] * [[https://balamaci.ro/reactive-log-processing/|Reactive log stream processing with RxJava – Part I]], [[https://balamaci.ro/reactive-log-stream-processing-with-rxjava-part-2/|Part II]] * [[https://ordina-jworks.github.io/reactive/2016/12/12/Reactive-Programming-Spring-Reactor.html|Reactive Programming with Spring Reactor]] * [[youtube>rdgJ8fOxJhc|Reactive Web Applications with Spring 5 by Rossen Stoyanchev]] Note that [[http://tomcat.apache.org/whichversion.html#Apache_Tomcat_8.x|Tomcat 8.x or higher supports Servlet v3.1]], see also [[stackoverflow>40964700|Spring reactor & Netty vs Tomcat]]. ===== Java and TCP/IP stack ===== * [[http://jnetpcap.com/|jNetPcap]] -- a java wrapper for ''libpcap'' and ''winpcap'' (see also [[http://www.javalobby.org/java/forums/t100034.html|jNetPcap]]) * [[http://sourceforge.net/projects/javappp/|JavaPPP]] ===== Questions answered ===== === What Java decompiler is the best? === * As to [[stackoverflow>3898391|Choose and test java decompiler]] the winner is [[http://java.decompiler.free.fr/|JD]]. * [[habrahabr>176825|Декомпиляция Java приложений]] suggests [[stackoverflow>6813729|Fernflower]]. * See also [[wp>Category:Java_decompilers|Java decompilers category]] and [[stackoverflow>26304492/decompiler-supporting-java-8|Decompiler supporting Java 8]]. * [[http://www.javadecompilers.com/|Online Java decompilers]] * [[habrahabr>176825|Декомпиляция Java приложений]] Hints how to enable code re-alignment (from [[stackoverflow>1905446|How to debug compiled Java code in Eclipse]]): * [[http://mchr3k-coding.blogspot.co.uk/2012/07/realignment-for-jd-eclipse.html|Realignment for JD-Eclipse]] * [[http://gauchoacomecable.wordpress.com/2011/10/14/eclipse-debug-java-without-source-code-jd-eclipse-and-realignment/|Debug java program without source code – jd-eclipse and realignment]] === What are the faster alternatives to Java Collections? === See [[stackoverflowa>632525/267197|Most efficient Java Collections library]] -- [[http://pcj.sourceforge.net/|PCJ]] vs [[http://trove4j.sourceforge.net/|Trove]]. === What is faster alternative to ''[[javase>docs/api/java/util/Stack.html|java.util.Stack]]''? === ''[[javase>docs/api/java/util/Stack.html|java.util.Stack]]'' is known to be based on ''[[javase>docs/api/java/util/Vector.html|java.util.Vector]]'' and thus is slow. What are the faster alternatives? From [[stackoverflowa>1320230/267197|java.util.Stack appropriate data structure]]: Use ''[[javase>docs/api/java/util/Deque.html|java.util.Deque]]'' interface implementations (''push()'', ''peek()'' and ''remove()'' operations). ''[[javase>docs/api/java/util/ArrayDeque.html|java.util.ArrayDeque]]'' does not support ''null'' elements in contrast to ''[[javase>docs/api/java/util/LinkedList.html|java.util.LinkedList]]''. Apache ''org.apache.commons.collections.ArrayStack'' is better then ''java.util.ArrayDeque'', but it is not generalized (check [[stackoverflowa>754380/267197|Using generics with commons collections]]). === [[stackoverflow>2895342|How can I split/partition a list in multiple lists (chunks) of given size?]] === If the list is not going to be mutated while processing of chunks the most effective is to create a view over the original list using ''[[javase>docs/api/java/util/List.html#subList(int, int)|List#subList(int fromIndex, int toIndex)]]'' ''[[https://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/ListUtils.html#partition%28java.util.List,%20int%29|ListUtils#partition(List list, int size]]'' also works in effective way and is based on ''List#subList(int, int)'': import org.apache.commons.collections4.ListUtils; List> chunkedList = ListUtils.partition(sourceList, chunkSize); === How to instantiate empty ''[[javase>docs/api/java/util/Enumeration.html|java.util.Enumeration]]'' instance? === import org.apache.commons.collections4.FluentIterable; Enumeration e = FluentIterable. empty().asEnumeration(); import org.apache.commons.collections4.IteratorUtils; Enumeration e = IteratorUtils.asEnumeration(Collections.emptyListIterator()); === [[stackoverflowa>4594600/267197|How to expand variables in a string?]] === import org.springframework.util.PropertyPlaceholderHelper; PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}"); String interpolatedValue = helper.replacePlaceholders(stringToBeInterpolated , System.getProperties()); === [[stackoverflowa>4594600/267197|How to match given path against Ant path pattern?]] === import org.springframework.util.AntPathMatcher; new AntPathMatcher().match(pattern, path); // e.g. match("/**/user/*", "/global/user/12"); === [[stackoverflow>4874626|How to escape HTML string?]] === ''[[https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringEscapeUtils.html#escapeHtml4-java.lang.String-|StringEscapeUtils#escapeHtml4(str)]]'' or (if you need more control) ''[[https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#replaceEach-java.lang.String-java.lang.String:A-java.lang.String:A-|StringUtils.replaceEach(str, new String[]{"&", "\"", "<", ">"}, new String[]{"&", """, "<", ">"})]]''. === [[stackoverflow>14526320|URI does not escape plus (+) in query]] === For example ''?q=word+word'' should become ''?q=word%2bword''. The challenge for URI is that once it receives query as a e.g. constructor argument, it's too late to understand the semantic of it, because query is already a string with all key-value pairs joined. As ''+'' is a special character as to [[https://tools.ietf.org/html/rfc2396#section-2.2|RFC 2396]] it does not need to be escaped. For example, consider query ''?key+=+val'' which is interpreted as ''?key = val'' at server side and that is perhaps the desired effect. Other builders work on higher semantic level (one can pass query parameter name and value separately), thus can do smarter escaping (at least to control it). Nevertheless they could have different views on what should be escaped: import org.springframework.web.util.UriComponentsBuilder; import javax.ws.rs.core.UriBuilder; System.out.println(UriComponentsBuilder.fromHttpUrl("http://host.com/path").queryParam("q", "my+zip%20/?&").build().encode().toUri()); System.out.println(UriComponentsBuilder.fromHttpUrl("http://host.com/path{suffix}").path("{sub}").queryParam("q", "{value}").buildAndExpand("/group%31?", "/id%41?", "my+zip%20/?&").encode().toUri()); System.out.println(); System.out.println(UriBuilder.fromUri("http://host.com/path").queryParam("q", "my+zip%20/?&").build()); System.out.println(UriBuilder.fromUri("http://host.com/path{suffix}").path("{sub}").queryParam("q", "{value}").build("/group%31?", "/id%41?", "my+zip%20/?&")); produces output: http://host.com/path?q=my%2Bzip%2520/?%26 http://host.com/path/group%2531%3F/id%2541%3F?q=my%2Bzip%2520/?%26 http://host.com/path?q=my%2Bzip%20%2F?%26 http://host.com/path%2Fgroup%2531%3F/%2Fid%2541%3F?q=my%2Bzip%2520%2F?%26 === How to implement timeout for socket ''write()'' operation? === The problem is that calling ''Thread#interrupt()'' on a blocked in the read thread has no effect (see [[stackoverflowa>1820190/267197|Interrupting a thread that waits on a blocking action?]]). The solution is either launch a separate thread as watchdog or [[stackoverflow>1338885|use non-blocking I/O]]: register selector for ''OP_WRITE'' events and select with timeout. import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; final long WRITE_TIMEOUT_MS = 2000; // 2 seconds SocketChannel channel = SocketChannel.open(); Selector selector = Selector.open(); channel.connect(new InetSocketAddress()); channel.configureBlocking(false); // switch to non-blocking after connection has succeeded channel.register(selector, SelectionKey.OP_WRITE); while (true) { int readyChannels = selector.select(WRITE_TIMEOUT_MS); if (readyChannels == 0) { continue; } for (Iterator iter = selector.selectedKeys().iterator(); iter.hasNext();) { SelectionKey key = iter.next(); if (key.isValid() && key.isWritable()) { // a channel is ready for writing channel.write(buffer); } // remove the key thus marking it as processed: iter.remove(); } } === [[stackoverflowa>31123016/267197|Read error response body in Java]] === Java ''HttpURLConnection'' returns body input stream via ''[[javase>docs/api/java/net/URLConnection.html#getInputStream%28%29|URLConnection#getInputStream()]]'' if HTTP response code was 2xx or 3xx, and ''[[javase>docs/api/java/net/HttpURLConnection.html#getErrorStream%28%29|HttpURLConnection#getErrorStream()]]'' otherwise. ''getInputStream()'' can throw the exception which was remembered during negotiation phase. When output streaming is enabled, authentication and redirection cannot be handled automatically (check ''[[javase>docs/api/java/net/HttpURLConnection.html#HttpURLConnection#setFixedLengthStreamingMode%28int%29|]]''), which results an exception when trying to read or write a body. === Headers like ''Origin'' or ''Content-Length'' cannot be set on ''[[javase>docs/api/java/net/HttpURLConnection.html|java.net.HttpURLConnection]]'' === If one tries to set the given header like this: connection.setRequestProperty("Origin", "localhost"); it has no effect. [[stackoverflow>13266620/267197|The solution]] is to set the following system property: -Dsun.net.http.allowRestrictedHeaders=true === Sending / receiving [[wp>MIME#Multipart_messages|multipart messages]] === ^ Library ^ Can read/unmarshall multipart message ^ Can create / marshall multipart message ^ | [[https://james.apache.org/mime4j/|Apache mime4j]] | :YES: | :YES: | | [[https://hc.apache.org/httpcomponents-client-ga/|Apache HTTP client]] | :NO: | :YES: | | [[https://commons.apache.org/proper/commons-fileupload/|Apache FileUpload]] | :YES: | :NO: | | [[springdocs>mvc.html#mvc-multipart|Spring]] | :YES: via [[https://commons.apache.org/proper/commons-fileupload/|Apache FileUpload]] or Servlet 3.0 API | :YES: in Spring 5 using reactive API (''[[springjava>http/codec/multipart/MultipartHttpMessageWriter.html|MultipartHttpMessageWriter]]'') | **Sending the message from prepared message template:** --SgkN_pfgxWH2sRuHgygqYkEQgctzP9HK0s5 Content-Disposition: form-data; filename="text-part" Content-Type: text/plain; charset=UTF-8 This is a message! --SgkN_pfgxWH2sRuHgygqYkEQgctzP9HK0s5-- * import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import org.apache.commons.io.IOUtils; private void requestMultipartRestTemplate() throws URISyntaxException, IOException { RestTemplate restTemplate = new RestTemplate(); byte[] message = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("multipart.txt")); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(HttpHeaders.CONTENT_TYPE, "multipart/form-data; boundary=SgkN_pfgxWH2sRuHgygqYkEQgctzP9HK0s5"); httpHeaders.setContentLength(message.length); httpHeaders.setAccept(Collections.singletonList(MediaType.MULTIPART_FORM_DATA)); ResponseEntity httpResponse = restTemplate.postForEntity( new URI("http://host.com/path"), new HttpEntity<>(message, httpHeaders), byte[].class); System.out.println(httpResponse.getStatusCode()); System.out.println(IOUtils.toString(httpResponse.getBody(), "UTF-8")); } * import org.springframework.http.HttpHeaders; import org.apache.commons.io.IOUtils; private static void requestMultipartURLConnection() throws URISyntaxException, IOException { byte[] message = IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("multipart.txt")); HttpURLConnection connection = (HttpURLConnection) new URL("http://host.com/path").openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, "multipart/form-data; boundary=SgkN_pfgxWH2sRuHgygqYkEQgctzP9HK0s5"); connection.setRequestProperty(HttpHeaders.CONTENT_LENGTH, Integer.toString(message.length)); try (OutputStream os = connection.getOutputStream()) { IOUtils.write(message, os); } System.out.println(connection.getResponseCode() + " " + connection.getResponseMessage()); InputStream is = null; try { is = connection.getErrorStream(); if (is == null) { is = connection.getInputStream(); } System.out.println(IOUtils.toString(is, "UTF-8")); } finally { IOUtils.closeQuietly(is); } } **Constructing and sending the message on the fly using [[https://hc.apache.org/httpcomponents-client-ga/|Apache HTTP client]]:** import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.commons.io.IOUtils; private static void requestMultipartApacheClient() throws URISyntaxException, IOException { HttpPost httpPost = new HttpPost("http://host.com/path"); MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create(); httpPost.setEntity(multipartBuilder.addTextBody("text-part", "This is a message!", ContentType.TEXT_PLAIN).build()); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); System.out.println(httpResponse.getStatusLine()); System.out.println(IOUtils.toString(httpResponse.getEntity().getContent(), StandardCharsets.UTF_8)); } **Receiving using [[https://commons.apache.org/proper/commons-fileupload/|Apache FileUpload]]:** import org.apache.commons.fileupload.MultipartStream; import org.apache.commons.lang3.ObjectUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpInputMessage; import org.springframework.http.MediaType; import org.springframework.util.Assert; private static final Pattern CONTENT_TYPE_HEADER = Pattern.compile(HttpHeaders.CONTENT_TYPE + ":\\s*([^\r\n]+)", Pattern.CASE_INSENSITIVE); static class StringMultipart extends ArrayList { } private static StringMultipart readMultipart(HttpInputMessage inputMessage) throws IOException { String boundary = inputMessage.getHeaders().getContentType().getParameter("boundary"); Assert.notNull(boundary, "boundary parameter should be specified"); ArrayList result = new ArrayList<>(); try (InputStream is = inputMessage.getBody(); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { MultipartStream multipartStream = new MultipartStream(is, boundary.getBytes(StandardCharsets.US_ASCII)); multipartStream.setHeaderEncoding(StandardCharsets.US_ASCII.toString()); boolean nextPart = multipartStream.skipPreamble(); while (nextPart) { String headers = multipartStream.readHeaders(); Matcher headerMatcher = CONTENT_TYPE_HEADER.matcher(headers); Charset bodyCharset = ObjectUtils.defaultIfNull( headerMatcher.find() ? MediaType.parseMediaType(headerMatcher.group(1)).getCharset() : null, StandardCharsets.UTF_8); multipartStream.readBodyData(baos); result.add(baos.toString(bodyCharset.toString())); baos.reset(); nextPart = multipartStream.readBoundary(); } } return result; } **Sending/receiving using [[https://james.apache.org/mime4j/|Apache mime4j]]:** import org.apache.james.mime4j.dom.Message; import org.apache.james.mime4j.dom.Multipart; import org.apache.james.mime4j.field.Fields; import org.apache.james.mime4j.message.BodyPartBuilder; import org.apache.james.mime4j.message.DefaultMessageWriter; import org.apache.james.mime4j.message.MultipartBuilder; import org.apache.james.mime4j.stream.EntityState; import org.apache.james.mime4j.stream.Field; import org.apache.james.mime4j.stream.MimeTokenStream; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.MimeType; import org.springframework.web.client.RestTemplate; public void requestMultipartApacheMime4jSpring() throws IOException { Multipart multipart = MultipartBuilder.create().setSubType("form-data") .addBodyPart(BodyPartBuilder.create().setBody("This is a message!", StandardCharsets.UTF_8) .setField(Fields.contentType("text/plain; charset=UTF-8")) .setContentDisposition("form-data", "text-part").build()) .build(); Message message = Message.Builder.of().setBody(multipart).build(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); new DefaultMessageWriter().writeBody(message.getBody(), bos); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentLength(bos.size()); httpHeaders.setAccept(Collections.singletonList(MediaType.MULTIPART_FORM_DATA)); for (Field field : message.getHeader()) { httpHeaders.add(field.getName(), field.getBody()); } System.out.println(httpHeaders.toString()); System.out.println(new String(bos.toByteArray(), StandardCharsets.UTF_8)); ResponseEntity responseEntity = new RestTemplate().postForEntity( "http://host.com/path", new HttpEntity<>(bos.toByteArray(), httpHeaders), byte[].class); MimeTokenStream mimeTokenStream = new MimeTokenStream(); mimeTokenStream.parseHeadless(new ByteArrayInputStream(responseEntity.getBody()), responseEntity.getHeaders().getContentType().toString()); do { if (mimeTokenStream.getState() == EntityState.T_BODY) { System.out.println(IOUtils.toString(mimeTokenStream.getInputStream(), ObjectUtils.defaultIfNull(MimeType .valueOf(mimeTokenStream.getBodyDescriptor().getMimeType()).getCharset(), StandardCharsets.UTF_8))); } } while (mimeTokenStream.next() != EntityState.T_END_OF_STREAM); } See also: [[rfc>rfc2045|RFC 2045]], [[rfc>rfc2046|RFC 2046]]. === What channels support non-blocking I/O in Java7? === Pipes and sockets support non-blocking I/O via ''select()'' mechanism (implement ''[[javase>docs/api/java/nio/channels/SelectableChannel.html|java.nio.channels.SelectableChannel]]''), and ''[[javase>docs/api/java/nio/channels/AsynchronousFileChannel.html|java.nio.channels.AsynchronousFileChannel]]'' supports non-blocking I/O using ''[[javase>docs/api/java/util/concurrent/Future.html|java.util.concurrent.Future]]'' interface. See [[stackoverflowa>3955899/267197|Why FileChannel in Java is not non-blocking?]] === [[stackoverflow>634564|How to created and utilize a named pipe?]] === In Java it is not possible to create a [[wp>named pipe]] one can do it by calling ''%%Runtime.exec("mkfifo")%%'' in Linux or using [[https://github.com/java-native-access/jna/blob/master/contrib/platform/test/com/sun/jna/platform/win32/Kernel32NamedPipeTest.java|JNA]] in Windows. Consuming the existing pipe is done in usual way: FileInputStream pipeStream = new FileInputStream("\\\\.\\pipe\\my_pipe"); ... pipeStream.close(); === How to define a location for temporary directory? === Unfortunately, JVM does not initialize ''java.io.tmpdir'' system variable from ''TMP'' or ''TEMP'' environment variable for any OS except Windows (see [[stackoverflowa>1925501/267197|Environment variable to control ''java.io.tmpdir'']]). So to be compatible pass ''-Djava.io.tmpdir=/work'' to your JDK. === [[stackoverflow>13632362|How to terminate Java application gracefully?]] === ''taskkill /t'' will not terminate Java process started by ''start /b''. And ''taskkill /f'' will kill the process without letting shutdown hooks to run. Listen on socket, pipe or check existence of a file and perform graceful termination programmatically. === How to generate PDF from HTML+CSS? === * [[github>flyingsaucerproject/flyingsaucer|Flying Saucer]] -- a wrapper for [[http://itextpdf.com/|iText]] * [[stackoverflow>235851/267197|Using itext to convert HTML to PDF]] * [[stackoverflowa>14853355/267197|Using iText, how can I apply CSS to my PDF document using CssResolver and CssFile?]] * [[http://wkhtmltopdf.org/|wktopdf]] -- CLI utility which needs a wrapper * [[http://www.pd4ml.com/|PD4ML]] -- not free/OSS === Where can I get JAI? === * [[http://download.java.net/media/jai/builds/release/1_1_3/|Installation packages]] for Linux ×32/×64, Windows ×32 and Solaris ×32/×64. * [[https://java.net/projects/jai-core/sources/svn/show/trunk/src/share/mediaLib/windows/i386|JAI native code for Windows ×32]] * [[https://java.net/projects/jai-core/sources/svn/show/trunk/src/share/mediaLib/windows/i386?rev=68|JAI MMX checker]] * [[http://download.java.net/media/jai/builds/release/1_1_3/INSTALL.html|JAI installation instructions]] * [[stackoverflow>5207145|JAI and ImageIO for 64 bit Windows]] As Maven artifacts for JAI are brocken, use alternative / clones: * [[github>haraldk/TwelveMonkeys|TwelveMonkeys ImageIO]] -- a collection of plugins and extensions for Java's ImageIO. * [[github>jai-imageio/jai-imageio-core|JAI ImageIO Core]] -- a community fork of the original ''java.net'' project ''jai-imageio-core''. * [[github>sgoeschl/java-image-processing-survival-guide/tree/master/paper|The Java Image Processing Survival Guide]] ([[github>sgoeschl/java-image-processing-survival-guide/blob/master/slides/jipsg.pdf|slides]]) === Where do "interned" string values are stored? Can they be GC'ed? === Each time you call ''[[javase>docs/api/java/lang/String.html#intern()|String#intern()]]'' the Java allocates the memory on the PermGen space. If you have a very heavy application with tons of classes, the classes are competing with the interned strings on the space. While the GC does clean up the permgen space (at least on Sun JDK), it does it only in a "stop the world" GC and not in a CMS which you typically configure your webapp or desktop to. Bottom line: items in the intern pool can be GC'd, but it's complex and unusual. * See [[http://www.javatuning.com/myth-busting-string-intern-object-allocations-are-never-garbage-collected/#comment-1696|Myth busting – ''String.intern()'' object allocations are never garbage collected]] and [[http://www.coderanch.com/t/438724/java/java/Garbage-Collection-String#1951427|Garbage Collection for String]]. * ''[[http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Interners.html|Interners]]'' class is an alternative implementation of [[javase>docs/api/java/lang/String.html#intern()|String#intern()]]. * For dummy explanation of interned strings see [[http://weblogs.java.net/blog/enicholas/archive/2006/06/all_about_inter.html|All about intern()]] (translated: [[habrahabr>79913|Все о String.intern()]]). === What's the semantic difference between ''[[grepcode>repo1.maven.org/maven2/commons-lang/commons-lang/2.6/org/apache/commons/lang/NotImplementedException.java|org.apache.commons.lang.NotImplementedException]]'' and ''[[javase>docs/api/java/lang/UnsupportedOperationException.html|java.lang.UnsupportedOperationException]]''? === //Not implemented// means "not yet implemented, but presumably will be eventually". Is typically static and nothing the client can do to change it. \\ //Unsupported// means "cannot be implemented because the operation doesn't make sense to support". Is typically state driven (e.g ''Bicycle.drive(fish)''). See also [[apachetracker>LANG-769|Restore NotImplementedException and UnhandledException]]. === What is the best way to handle ranges of numbers? === Have a look at ''[[http://commons.apache.org/lang/api-release/org/apache/commons/lang3/Range.html|Range]]'' API in Apache Commons Lang and ''[[http://docs.guava-libraries.googlecode.com/git/javadoc/index.html?com/google/common/collect/Ranges.html|Ranges]]'' in Guava Collections (see [[stackoverflowa>7721439/267197|Ranges in Java, what's the best approach?]]). If that API is not enough, you need [[wp>Interval tree]] implementation (see [[stackoverflowa>1580441/267197|Data structure for quick interval look up]], [[stackoverflow>1418150|IntervalTree Java implementation]], [[http://www.thekevindolan.com/2010/02/interval-tree/index.html|Interval Tree Java Implementation]]). === [[stackoverflow>747539|Is there Java library for accessing serial ports?]] === From [[http://en.wikibooks.org/wiki/Serial_Programming/Serial_Java|Serial Programming/Serial Java]]: * [[http://mfizz.com/oss/rxtx-for-java|RXTX for Java]] -- native library providing serial and parallel communication * [[https://github.com/scream3r/java-simple-serial-connector|JSSC]] (Java Simple Serial Connector) See also: * [[http://www.lammertbies.nl/comm/info/RS-232_null_modem.html|RS232 serial null modem cable wiring]], [[http://www.camiresearch.com/Data_Com_Basics/New_Cable_pdfs/3.pdf|DB9 null modem]] * [[https://en.wikibooks.org/wiki/Serial_Programming/RS-232_Connections|Serial Programming/RS-232 Connections]] === How to access private fields? === Here comes the code that allows to do that: /** * Get the value of private field {@code fieldName} of given object {@code target}. */ public static T getPrivateField(Object target, String fieldName) { try { return getPrivateField(target, target.getClass(), fieldName); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } } /** * Get the value of private field {@code fieldName} of given object {@code target} which is treated as class * {@code clazz}. * * @throws NoSuchFieldException * if given field was not found */ @SuppressWarnings("unchecked") private static T getPrivateField(Object target, Class clazz, String fieldName) throws NoSuchFieldException { try { Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); return (T) field.get(target); } catch (NoSuchFieldException e) { if (clazz.getSuperclass() == Object.class) { // Field is really not found: throw e; } // Try super class: return getPrivateField(target, clazz.getSuperclass(), fieldName); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } The same, but using Spring utility methods: import org.springframework.util.ReflectionUtils; /** * Get the value of private field {@code fieldName} of given object {@code target}. */ @SuppressWarnings("unchecked") public static T getField(Object target, String fieldName) { Field field = ReflectionUtils.findField(target.getClass(), fieldName); ReflectionUtils.makeAccessible(field); return (T) ReflectionUtils.getField(field, target); } The same, but using Apache Commons Lang utility methods: import org.apache.commons.lang3.reflect.FieldUtils; /** * Get the value of private field {@code fieldName} of given object {@code target}. */ @SuppressWarnings("unchecked") public static T getField(Object target, String fieldName) { try { return (T) FieldUtils.readField(target, fieldName, true); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } === [[https://www.toptal.com/java/interview-questions#iquestion-43|Tail recursion is functionally equivalent to iteration. Since Java does not yet support tail call optimization, describe how to transform a simple tail recursive function into a loop and why one is typically preferred over the other.]] === Here is an example of a typical recursive function, computing the arithmetic series 1, 2, 3…N. Notice how the addition is performed after the function call. For each recursive step, we add another frame to the stack. public int sumFromOneToN(int n) { if (n < 1) { return 0; } return n + sumFromOneToN(n - 1); } [[wp>Tail call|Tail recursion]] occurs when the recursive call is in the tail position within its enclosing context -- after the function calls itself, it performs no additional work. That is, once the base case is complete, the solution is apparent. For example: public int sumFromOneToN(int n, int a) { if (n < 1) { return a; } return sumFromOneToN(n - 1, a + n); } Here you can see that a plays the role of the accumulator -- instead of computing the sum on the way down the stack, we compute it on the way up, effectively making the return trip unnecessary, since it stores no additional state and performs no further computation. Once we hit the base case, the work is done -- below is that same function, "unrolled". public int sumFromOneToN(int n) { int a = 0; while(n > 0) { a += n--; } return a; } Another example of not tail recursion (classical): int factorial(int n) { return (n == 0) ? 1 : n * factorial(n - 1); } int fac_times(int n, int acc) { return (n == 0) ? acc : fac_times(n - 1, acc * n); } int factorial(int n) { return fac_times(n, 1); } Many functional languages natively support tail call optimization, however JVM does not. In order to implement recursive functions in Java, we need to be aware of this limitation to avoid StackOverflowErrors. In Java, iteration is almost universally preferred to recursion. {{tag>Spring AspectJ}}