background preloader

LANG

Facebook Twitter

Développons en Java. Code Reuse: Action and Context Reuse. I hardly need to argue why reusing code is beneficial. Code reuse (usually) leads to faster development and less bugs. Once a piece of code is encapsulated and reused, there is less code to check for correctness. If database connections are only opened and closed in a single place throughout your application it is a lot easier to assure that the connection handling works correctly. But I'm sure you already know all this. There are two types of code reuse. The first type, action reuse, is the most commonly seen type of reuse. The second type, context reuse, is the reuse of a common context (set of instructions) inbetween which different actions take place.

Action Reuse Action reuse is the most commonly seen type of reuse. Public List readUsersOfStatus(String status){ Connection connection = null; String sql = "select * from users where status = ? " The experienced developer can quickly see that the two blocks of code marked in bold are identical and thus can be encapsulated and reused. Java.util.prefs Preferences. A typical installer for an application needs to ask the user a couple of options and some of these are configuration questions e.g. the port on which the application should run, how it should run etc. The application has to remember these options and use them in every run. Standard manner of solving such a problem is to write these options in a properties file which can be loaded at the start-up of the application. But then again the problem shifts to some other area i.e. remember the install path and then load the required properties file from the installed path. Remembering installed path can be solved by setting an environment variable e.g.

MYAPP_HOME. The variable can be initialized with the required value while installing so that every time the application gets loaded the variable will be set. The Other Solution The Preferences API that is provided JDK can be used to solve this typical problem. Writing a preference is straight forward. Related Articles : Related Whitepaper: Java I/O Streams and Channels. 15.3. Converting Between Streams and Channels Channels are cool, but streams aren't going away. In many cases, with small amounts of data, streams are just faster.

Other times, they're more . And sometimes they're part of a legacy API. For instance, I've seen a lot of XML libraries for Java. I've even written one or two, but I've yet to encounter one that uses buffers and channels. The java.nio.Channels class provides eight static utility for connecting channels to streams and vice versa. 15.3.1. The newInputStream( ) method converts any ReadableByteChannel , including FileChannel s, into an InputStream : public static InputStream newInputStream(ReadableByteChannel ch) You can use the methods of the InputStream class to read from the channel. XMLReader parser = XMLReaderFactory.createXMLReader( ); FileInputStream in = new FileInputStream("document.xml"); FileChannel channel = in.getChannel( ); Now say you want to pass this channel to the XML parser. At this point you may be objecting.

Zip File System Provider. Introduction The zip file system provider introduced in the Java SE 7 release is an implementation of a custom file system provider. The zip file system provider treats a zip or JAR file as a file system and provides the ability to manipulate the contents of the file. The zip file system provider creates multiple file systems — one file system for each zip or JAR file. The demo/nio/zipfs/src.zip file in your Java SE 7 installation contains the source code for the zip file system provider. It also contains the Demo.java class that shows how to use the zip file system provider. Using the Zip File System Provider You can use the factory methods of the java.nio.file.FileSystems class to create a new zip file system or to obtain a reference to an existing zip file system.

Specify the configuration options for the zip file system in the java.util.Map object passed to the FileSystems.newFileSystem method. Resources. Java NIO: NIO vs. IO. When studying both the Java NIO and IO API's, a question quickly pops into mind: When should I use IO and when should I use NIO? In this text I will try to shed some light on the differences between Java NIO and IO, their use cases, and how they affect the design of your code. Main Differences Betwen Java NIO and IO The table below summarizes the main differences between Java NIO and IO. I will get into more detail about each difference in the sections following the table. Stream Oriented vs. The first big difference between Java NIO and IO is that IO is stream oriented, where NIO is buffer oriented. Java IO being stream oriented means that you read one or more bytes at a time, from a stream.

Java NIO's buffer oriented approach is slightly different. Blocking vs. Java IO's various streams are blocking. Java NIO's non-blocking mode enables a thread to request reading data from a channel, and only get what is currently available, or nothing at all, if no data is currently available. Selectors. Fork/Join (The Java™ Tutorials > Essential Classes > Concurrency) The fork/join framework is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application. As with any ExecutorService implementation, the fork/join framework distributes tasks to worker threads in a thread pool.

The fork/join framework is distinct because it uses a work-stealing algorithm. Worker threads that run out of things to do can steal tasks from other threads that are still busy. The center of the fork/join framework is the ForkJoinPool class, an extension of the AbstractExecutorService class. ForkJoinPool implements the core work-stealing algorithm and can execute ForkJoinTask processes. Basic Use The first step for using the fork/join framework is to write code that performs a segment of the work. Blurring for Clarity Standard Implementations. ThreadLocal, partie 1, principes du stockage magique | Codes et autres, sauce java, parfum objet. Dans l’API java, on trouve une classe au comportement tout a fait particulier, ThreadLocal. Son principe: stocker des données dans le Thread courant afin de les récupérer plus tard, dans une autre méthode par exemple, sans avoir à les passer en argument à toute la chaine d’appel. Cette classe peut vous être d’un grand secours, mais elle doit être utilisée judicieusement et surtout en extrêmement précautionneusement!

La classe ThreadLocal est apparue dans le JDK1.2, vers la fin 1998 (et oui, elle est méconnue, mais elle date!). Son utilisation principale, permettre à plusieurs threads de travailler simultanément sur une variable statique, tout en permettant à chaque Thread d’avoir sa propre instance de la variable ainsi qu’éventuellement, proposer un constructeur pour créer la valeur par défaut pour les threads qui n’en ont pas encore recu. Exemple, soit la classe suivante utilisée par 2 Threads: La première implémentation (jdk 1.2) de cette classe était assez simple. Java Practices. Jenkov.com - Software and Tutorials for Software Developers. Java Exception Handling Tutorial. Java exception handling enables your Java applications to handle errors sensibly. Exception handling is a very important yet often neglected aspect of writing robust Java applications or components.

When an error occurs in a Java program it usually results in an exception being thrown. How you throw, catch and handle these exception matters. There are several different ways to do so. Not all are equally efficient and fail safe. This trail (set of articles) digs deeper into exception handling in Java. The trail covers various do's and dont's of Java exception handling. The versions of Java used in this tutorial are Java 6 and Java 7, though most of the techniques here work already from Java 5 and forward. Below follows a quick introduction to what you can learn in this Java exception handling trail. Basic Java Exception Handling The first 2 texts on Java exception handling covers the basics of Java's exception throwing and catching mechanism, and exception hierarchies.

Checked vs.