{{announcement.body}}
{{announcement.title}}

SKP's Java/Java EE Gotchas: Revisiting Java SE 9 Features, Part 2

DZone 's Guide to

SKP's Java/Java EE Gotchas: Revisiting Java SE 9 Features, Part 2

As I had promised, albeit very late, I am back with the Code Samples of my earlier article Java SE 9... What's New? — code samples for all features.

· Java Zone ·
Free Resource

As I had promised, albeit very late, I am back with the Code Samples of my earlier article Java SE 9... What's New? You may refer to the earlier article to understand the newly introduced features at a High Level. This article provides the concluding code samples for each of the features.

You may also like: SKP's Java/Java EE Gotchas: Revisiting Java SE 9 Features, Part 1

You may Download the Code Samples for the following New Features Here. (Import as Eclipse Project, Set Compiler/Environment as Java 9. Run the Main Class 'Java9Application' to see the Output/Outcome of the Code Samples.)

B. Core Library Changes in Java 9 (Continued) 

09. Stack-Walking API

Prior to Java 9, The way to access Stack Trace was very limited and provided the entire dump or stack information at once. This was inefficient and did not allow any direct way of filtering data. With Java 9, a Lazy StackWalker API has been introducedThis will allow fetching data based on filtering conditions and is more efficient. 

Java
 




x
77


 
1
 package com.techilashots.java9.features;  
2
 import java.lang.StackWalker.Option;  
3
 import java.util.List;  
4
 import java.util.stream.Collectors;  
5
 
           
6
 /**  
7
  * Stack Walker API is a new feature of Java 9, aimed at Improving Performance of the predecessor Stack Track Element,  
8
  * as also for providing a way to filter the Stack Elements, in case of Exception or to Understand Application Behavior.   
9
  * Although, there have been multiple changes, I am covering only Stack Frame Attributes and also the walk() method   
10
  * for Walking the Stack Frame.   
11
  */  
12
 public class StackWalkingService { 
13
 
14
      private int databaseService() {  
15
 
           
16
           int x = 3;  
17
 
           
18
           // Usage 01: Walking All Stack Frames  
19
           System.out.println("Java 9 Stack Walker API — Showing All Stack Frames");  
20
           StackWalker stackWalker = StackWalker.getInstance();  
21
           stackWalker.forEach(System.out::println);  
22
           System.out.println("");  
23
 
           
24
           // Usage 02 : Filtering or Walking Stack Frames  
25
           System.out.println("Java 9 Stack Walker API — Walking / Filtering Stack Frames");  
26
           List<StackWalker.StackFrame> stackFrames;  
27
           stackFrames = stackWalker.walk(frames -> frames.limit(2).collect(Collectors.toList()));  
28
           stackFrames.forEach(System.out::println);  
29
           System.out.println("");  
30
 
           
31
           // Usage 03 : Show All Attributes of a Stack Frame  
32
           System.out.println("Java 9 Stack Walker API — Show All Attributes in Stack Frame");  
33
           StackWalker newWalker = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE);  
34
           stackFrames = newWalker.walk(frames -> frames.limit(1).collect(Collectors.toList()));  
35
           stackFrames.forEach(sfRecord->   
36
           {  
37
                System.out.printf("[Bytecode Index] %d%n", sfRecord.getByteCodeIndex());  
38
                System.out.printf("[Class Name] %s%n", sfRecord.getClassName());  
39
                System.out.printf("[Declaring Class] %s%n", sfRecord.getDeclaringClass());  
40
                System.out.printf("[File Name] %s%n", sfRecord.getFileName());  
41
                System.out.printf("[Method Name] %s%n", sfRecord.getFileName());  
42
                System.out.printf("[Is Native] %b%n", sfRecord.isNativeMethod());  
43
                System.out.printf("[Line Number] %d%n", sfRecord.getLineNumber());  
44
           });  
45
           return x;  
46
      }  
47
 
           
48
      private float persistenceService() {  
49
           float x = databaseService();  
50
           return x;  
51
      }  
52
 
           
53
      private double businessService() {  
54
           double x = persistenceService();  
55
           return x;  
56
      }  
57
 
           
58
      private double presentationService() {  
59
           long x = (long) businessService();  
60
           return x;  
61
      }  
62
 
           
63
      public void uiDisplay() {  
64
           System.out.println("Java 9 Stack Walker API for Debugging and Application Behavior");  
65
           double x = presentationService();  
66
           System.out.println("\n[Method to Display On User Interface]");  
67
           System.out.println("Old MacDonald had a Farm. In that Farm, He had " + x + " Cows!");  
68
      }  
69
 
           
70
      /**  
71
       * @param args  
72
       */  
73
      public static void main(String[] args) {  
74
           StackWalkingService stackWalkingService = new StackWalkingService();  
75
           stackWalkingService.uiDisplay();  
76
      }  
77
 } 



10. Compact Strings

Although this has no external ramification to a developer in terms of syntax or semantics change — It may impact the way we design for memory and performance. The current UTF-16 representation uses 2 Bytes for Storage. Most of the string contains characters that are only Latin-1 in nature. 

The Latin-1 characters require only 1 Byte for Storage. With Java 9, String storage has been modified to start with an Additional Encoding Flag. This flag indicates whether it contains ISO-8859-1/Latin-1 characters or the UTF-16 characters. As per the official word, it has to lead to an Improved Usage of Memory and Efficient GC, but with Some Loss in Performance at Peak Loads.

The Compact Strings are always enabled in Java 9, but it can be disabled by passing in the VM Argument +XX:-CompactStrings

It has to be noted that in Java 9, the implementation of java.lang.String decides at runtime, whether the storage size is to be 2 Bytes or 1 Byte, as per the actual String size (UTF-16 or Latin-1 Character).

11. Spin-Wait Hints

For multi-threading applications, this brings in some performance improvements under Busy-Waiting or Spin-Waiting conditions. Usually, Busy-Waiting is done for synchronization of some state of the object between two or more invokers — Waiting for a condition to occur before processing starts or continues. Thread.onSpinWait() has been introduced as a static method in the Thread class and can be optionally called in Busy-Waiting loops — This will allow the JVM to issue processor instructions on some system architectures to improve Reaction Time in such Spin-Wait Loops and also Reduce the Power Consumed by the Core Thread or Hardware thread. This benefits the Overall Power Consumption of a Program, and possibly Allowing other Cores or Hardware Threads to execute at Faster Speeds within the Same Power Consumption Envelope.

Java
 




xxxxxxxxxx
1
84


 
1
 package com.techilashots.java9.features;  
2
 
           
3
 import java.util.List;  
4
 import java.util.Vector;  
5
 
           
6
 /**  
7
  * For a Single Line Demonstration, I wrote the Non-Pure Threaded form of Producer-Consumer. Run the Code Multiple Times  
8
  * On a Machine, where you can Understand how the Temperature Changes and Extra Cooling Fan Kicks Off. Even though I did  
9
  * not do it myself, Take it up as an Experiment, by removing the Thread.onSpinWait() [Compare Before/After and also try  
10
  * with Data Set of 1 Million to 10 Million]  
11
  *   
12
  * Thread.onSpinWait() will Optimize Latency and Reduce/Optimize Power Consumption  
13
  */  
14
 public class SpinWaitHints {  
15
 
           
16
      public static void main(String[] args) {  
17
           List<String> itemQueue = new Vector<String>();  
18
           Producer producer = new Producer(itemQueue);  
19
           Consumer consumer = new Consumer(itemQueue);  
20
           producer.start();  
21
           consumer.start();  
22
      }  
23
 }  
24
 class Producer extends Thread {  
25
 
           
26
      List<String> itemQueue;  
27
      Producer(List<String> itemQueue) {  
28
           this.itemQueue = itemQueue;  
29
      }  
30
      public void run() {  
31
           try {  
32
                produce();  
33
           } catch (InterruptedException e) {  
34
                e.printStackTrace();  
35
           }  
36
      }  
37
      public void produce() throws InterruptedException {  
38
           while (true) {  
39
                while (itemQueue.size() < 100000) // produce 1 lac items  
40
                {  
41
                     String item = "Sumith Puri " + (itemQueue.size());  
42
                     itemQueue.add(item);  
43
                     System.out.println("Item Produced: " + item);  
44
                }  
45
                while (itemQueue.size() > 0) {  
46
                     // spin waiting — x86 architectures will now optimize  
47
                     Thread.onSpinWait();  
48
                }  
49
           }  
50
      }  
51
 }  
52
 
           
53
 class Consumer extends Thread {  
54
      List<String> itemQueue;  
55
      public Consumer(List<String> itemQueue) {  
56
           this.itemQueue = itemQueue;  
57
      }  
58
      public void consume() throws InterruptedException {  
59
           while (true) {  
60
                while (itemQueue.size() < 100000) {  
61
                     // spin waiting — x86 architectures will now optimize  
62
                     Thread.onSpinWait();  
63
                }  
64
                int x = itemQueue.size();  
65
                while (x >= 1) {  
66
                     x = x1;  
67
                     if (x >= 0) {  
68
                          String item = itemQueue.remove(x);  
69
                          System.out.println("Item Consumed: " + item);  
70
                     }  
71
                }  
72
                if (itemQueue.size() > 0)  
73
                     itemQueue.remove(0);  
74
           }  
75
      }  
76
 
           
77
      public void run() {  
78
           try {  
79
                consume();  
80
           } catch (InterruptedException e) {  
81
                e.printStackTrace();  
82
           }  
83
      }  
84
 }  



12. New Version-String Scheme

From Java 9, $MAJOR.$MINOR.$SECURITY.$PATCH  is the naming scheme for releases in Java. These details are also contained in the Runtime.Version Class. From Java 9, $MAJOR.$MINOR.$SECURITY.$PATCH is the naming scheme for releases in Java. These details are also contained in the Runtime.Version Class.

Java
 




xxxxxxxxxx
1
19


 
1
 package com.techilashots.java9.features;  
2
 /**  
3
  * $MAJOR.$MINOR.$SECURITY+$BUILD is the Naming Scheme for Version String in Java.   
4
  */  
5
 public class JavaVersionStringChanges {  
6
      public void printVersionInformation() {  
7
           Runtime.Version versionInfo = Runtime.version();  
8
           System.out.println("Version String Changes in Java 9");  
9
           System.out.println("Major Version: " + versionInfo.major());  
10
           System.out.println("Minor Version: " + versionInfo.minor());  
11
           System.out.println("Security Version: " + versionInfo.security());  
12
           System.out.println("Build Version: " + versionInfo.build());  
13
           System.out.println("\nIn Java 9, Version Naming is Major.Minor.Security.Build");  
14
           System.out.println("Currently Running in Java Version: " + versionInfo.toString());  
15
      }  
16
      public static void main(String[] args) {  
17
           new JavaVersionStringChanges().printVersionInformation();  
18
      }  
19
 } 



13. Enhanced Method Handles

A method handle is a typed, directly executable reference to an underlying method, constructor, field, or similar low-level operation, with optional transformations of arguments or return values. These transformations are quite general and include such patterns as conversion, insertion, deletion, and substitution. In Java 9, Method Handles have been Enhanced to include static methods for creating a different kind of Method Handles.

Java
 




xxxxxxxxxx
1
54


 
1
package com.techilashots.java9.features;  
2
 import java.lang.invoke.MethodHandle;  
3
 import java.lang.invoke.MethodHandles;  
4
 
          
5
 /**  
6
  * MethodHandles were introduced first in Java 7. You have to think them as an alternative for Java Reflection API, but  
7
  * with an advantage of better performance as they are specified at creation time. Enhanced Method Handles has primarily  
8
  * added new static methods to better/widen the functionality provided by Method Handles.  
9
  *   
10
  * Note that Method Handles are Enhanced in Java 9, to introduce very many changes and methods. I will be covering the  
11
  * ones that are the most important, only to introduce this topic.   
12
  *   
13
  * arrayLength, arrayConstructor, zero, empty,   
14
  * loop, countedloop, iteratedloop, dowhileloop, whileloop, try/finally  
15
  */  
16
 public class EnhancedMethodHandles {  
17
 
          
18
      public void enhancedMethodHandleDemo() {  
19
 
          
20
           try { 
21
 
22
                // arrayLenth  
23
                MethodHandle methodHandleLength = MethodHandles.arrayLength(int[].class);  
24
                int[] ageArray = new int[] { 21, 28, 36 };  
25
                int arrayLength;  
26
                arrayLength = (int) methodHandleLength.invoke(ageArray);  
27
                System.out.println("Length of Array using Method Handle is " + arrayLength);  
28
                
29
                // arrayConstructor  
30
                MethodHandle methodHandleConstructor = MethodHandles.arrayConstructor(int[].class);  
31
                int[] newAgeArray = (int[]) methodHandleConstructor.invoke(3);  
32
                System.out.println("Array Constructed using Method Handle of Size " + newAgeArray.length);  
33
                
34
                // zero  
35
                int x = (int) MethodHandles.zero(int.class).invoke();  
36
                System.out.println("Default Value of Primitive Integer using Method Handles is " + x);  
37
                String y = (String) MethodHandles.zero(String.class).invoke();  
38
                System.out.println("Default Value of String using Method Handles is " + y);  
39
                
40
                System.out.println();  
41
                System.out.println("Reader/Developer - Left as an Exercise for You :-)");  
42
                System.out.println("Refer Loop, CountedLoop, DoWhileLoop, WhileLoop, IteratedLoop, TryFinally");  
43
           } catch (Throwable e) {  
44
                
45
                System.out.println("Was Hungry as Ever - Gulped Everything I Got!");  
46
           }  
47
           // refer to, https://goo.gl/JCyo7N (official javadoc)  
48
           // also use, https://goo.gl/i8wNJ8 (individual blog)  
49
      }  
50
 
          
51
      public static void main(String[] args) {  
52
           new EnhancedMethodHandles().enhancedMethodHandleDemo();  
53
      }  
54
 }  



14. Variable Handles

Java's Concurrent Package (java.util.concurrent.atomic) provide all Atomic Types for performing atomic operations. Apart from this,  Unsafe Operations (sun.misc.unsafe) such as creating objects without calling the constructor used in Java Low-Level Programming require to be hidden from the outside world as per JEP 260: Encapsulate Most Internal APIs

This has led to creation of a new abstract class type named VarHandle — This will allow a developer to assign different types to the same reference (dynamically typed reference). It can also take care of performing atomic operations on the held variable, including compare and swap (set or exchange) operations. It also provides memory fencing operations, to order the in-memory representation of the object, by providing finer grain control.

Firstly, You need to understand Memory Ordering Effects, as VarHandle is entirely based on the Understanding of Plain, Volatile, Opaque, Acquire/Release Memory Ordering Modes. You may refer to them at https://www.baeldung.com/java-variable-handles (Under Memory Ordering Effects). You have to try and visualize this correctly and then proceed to the Code Samples.

Java
 




xxxxxxxxxx
1
71


 
1
package com.techilashots.java9.features;  
2
 
          
3
 import java.lang.invoke.MethodHandles;  
4
 import java.lang.invoke.VarHandle;  
5
 
          
6
 /**  
7
  * VarHandle allows developers to assign different types to the same reference (dynamically typed reference).It can also   
8
  * take care of performing atomic operations on the held variable, including compare and swap (set/exchange) operations.   
9
  * It also provides memory fencing operations, to order the in-memory representation of the object, by providing finer   
10
  * grain control.   
11
  *   
12
  * I am providing an Example of the Read Operations using VarHandle. Please refer to the link provided below for further  
13
  * info on VarHandle on Public Variable, VarHandle for Private Variables, VarHandle for Array Types   
14
  *   
15
  * https://www.baeldung.com/java-variable-handles  
16
  */  
17
 class VarHandleStore {  
18
 
          
19
      public int varIntHandle01 = 5;  
20
      public int varIntHandle02 = 9;  
21
      public byte varByteHandle03 = 21;  
22
 }  
23
 
          
24
 public class VariableHandles {  
25
 
          
26
      public void useVariableHandle() {  
27
 
          
28
           System.out.println("Java 9 Introduces.... Variable Handles!");  
29
 
          
30
           try { 
31
 
          
32
                VarHandleStore varHandleStore = new VarHandleStore();  
33
                VarHandle varHandle = MethodHandles.lookup().in(VarHandleStore.class).findVarHandle(VarHandleStore.class,  
34
                          "varIntHandle01", int.class);  
35
                // value using get() in varhandle  
36
                int plainValue = (int) varHandle.get(varHandleStore);  
37
                System.out.println("Value using get() in VarHandle: " + plainValue);  
38
 
          
39
                // value is written to using set() — plain access  
40
                // you can also use set(), setOpaque(), setVolatile(), setRelease()  
41
                varHandle.set(varHandleStore, 21);  
42
                plainValue = (int) varHandle.get(varHandleStore);  
43
                System.out.println("Set Value using set(), then get() in VarHandle: " + plainValue);  
44
                
45
                // value is written to using getandadd()  
46
                int oldValue = (int) varHandle.getAndAdd(varHandleStore, 51);  
47
                plainValue = (int) varHandle.get(varHandleStore);  
48
                System.out.println("Using getAndAdd() in VarHandle, Old Value: " + oldValue + ", New Value: " + plainValue);  
49
                varHandle = MethodHandles.lookup().in(VarHandleStore.class).findVarHandle(VarHandleStore.class,  
50
                          "varIntHandle02", int.class);  
51
                
52
                // please do try out the compareandset() — atomic updates  
53
                // have left this due to time constraints  
54
                // value is written to using getandbitwiseor()  
55
                varHandle = MethodHandles.lookup().in(VarHandleStore.class).findVarHandle(VarHandleStore.class,  
56
                          "varByteHandle03", byte.class);  
57
                byte before = (byte) varHandle.getAndBitwiseOr(varHandleStore, (byte) 127);  
58
                byte after = (byte) varHandle.get(varHandleStore);  
59
                
60
                System.out.println("Get Byte Value, Then Or, using getAndBitwiseOr()");  
61
                System.out.println("Old Byte Value: " + before + "; New Byte Value: " + after);  
62
           } catch (NoSuchFieldException | IllegalAccessException e) {  
63
 
64
                e.printStackTrace();  
65
           }  
66
      }  
67
 
          
68
      public static void main(String[] args) {  
69
           new VariableHandles().useVariableHandle();  
70
      }  
71
 }  



15. Filter Incoming Serialization Data 

This feature is related to the addition of filters at the serialization incoming streams to improve security and robustness. The core mechanism is a filter interface implemented by serialization clients and set on an ObjectInputStream.

The filter interface methods are called during the de-serialization process to validate the classes being de-serialized, the sizes of arrays being created, and metrics describing stream length, stream depth, and a number of references as the stream are being decoded. 

The filter returns a status to accept, reject, or leave the status undecided. Some Helpful Information On this Feature can be found at https://goo.gl/bRezWt You have to remember the words Security, Vulnerabilities and Robustness as the main reasons behind the creation of this feature in Java. This will thwart possible Security Attacks like Denial Of Service.

The core mechanism is a Filter Interface implemented by serialization clients and set on an ObjectInputStream. The filter interface methods are called during the Deserialization Process to Validate the classes being Deserialized, The Sizes of Arrays being Created, The Stream Length, Graph Depth and Number of References as the Stream are being Decoded. 

A filter determines whether the arguments are ALLOWED or REJECTED and should return the appropriate status. If the filter cannot determine the status it should return UNDECIDED. Filters are designed for the specific use case and expected types. A filter designed for a particular user may be passed a class that is outside of the scope of the filter. If, for example, the purpose of the filter is to Black-List Classes then it can reject a candidate class that matches and report UNDECIDED for others.

Java
 




xxxxxxxxxx
1
42


 
1
package com.techilashots.java9.features;  
2
 
          
3
 import java.io.ObjectInputFilter;  
4
 
          
5
 /**  
6
  * Demonstrates Java 9 Serialization/De-Serialization Filters for Incoming Data. Do Refer https://goo.gl/bRezWt for more  
7
  * on Filters, with more Details and Examples.  
8
  */  
9
 class ItemCatalogFilter implements ObjectInputFilter {  
10
 
          
11
      private long maxStreamBytes = 400; // Maximum allowed bytes in the stream.  
12
      private long maxDepth = 2; // Maximum depth of the graph allowed.  
13
      private long maxReferences = 5; // Maximum number of references in a graph.  
14
 
          
15
      @Override  
16
      public Status checkInput(FilterInfo filterInfo) {  
17
 
          
18
           if (filterInfo.references() < 0 || filterInfo.depth() < 0 || filterInfo.streamBytes() < 0  
19
                     || filterInfo.references() > maxReferences || filterInfo.depth() > maxDepth  
20
                     || filterInfo.streamBytes() > maxStreamBytes) {  
21
                // reject this, as it seems malicious, incorrect or tampered with  
22
                return Status.REJECTED;  
23
           }  
24
 
          
25
           Class<?> clazz = filterInfo.serialClass();  
26
           if (clazz != null) {  
27
                if (CatalogCustomer.class == filterInfo.serialClass()) {  
28
                     // we are expecting a customer of our product catalog  
29
                     System.out.println("Incoming Serialization Data Verified for Structure and Vulnerabilities");  
30
                     return Status.ALLOWED;  
31
                } else {  
32
                     // seems like some tampered, unexpected or malicious data here  
33
                     return Status.REJECTED;  
34
                }  
35
           }  
36
 
          
37
           // the status as undecided, when we cannot infer — or + for sure  
38
           // left for the developer to decide as per business/security process  
39
           return Status.UNDECIDED;  
40
      }  
41
 }  



You may Download the Code Samples for the following New Features Here. (Import as Eclipse Project, Set the Compiler/Environment as Java 9. Make Sure that you Have Java 9 / JDK 9 Installed on your System. Run the Main Class 'Java9Application' to see the Output/Outcome of the Code Samples.)

Check out the Eclipse Console Output provided Below from Running the 'Java9Application' (Refer Attached Code Samples). Please refer to the Individual Classes, provided for each of the features to understand the features better. Go ahead — Add, Modify, Delete to Experiment with all of the New Java 9 Features. The Output for the Features Marked [01-08] is shown in Part 1 of the Article at Java SE 9... What's New? [Code Samples — 01/02].

Java
 




xxxxxxxxxx
1
82


 
1
 ================================  
2
 
          
3
 09. Stack Walking API  
4
 ---------------------  
5
 Java 9 Stack Walker API for Debugging and Application Behavior  
6
 Java 9 Stack Walker APIShowing All Stack Frames  
7
 com.techilashots.java9.features.StackWalkingService.databaseService(StackWalkingService.java:23)  
8
 com.techilashots.java9.features.StackWalkingService.persistenceService(StackWalkingService.java:57)  
9
 com.techilashots.java9.features.StackWalkingService.businessService(StackWalkingService.java:63)  
10
 com.techilashots.java9.features.StackWalkingService.presentationService(StackWalkingService.java:69)  
11
 com.techilashots.java9.features.StackWalkingService.uiDisplay(StackWalkingService.java:77)  
12
 com.techilashots.java9.main.Java9Application.stackWalkingAPI(Java9Application.java:321)  
13
 com.techilashots.java9.main.Java9Application.java9CoreLibraryChanges(Java9Application.java:106)  
14
 com.techilashots.java9.main.Java9Application.main(Java9Application.java:48)  
15
 Java 9 Stack Walker APIWalking / Filtering Stack Frames  
16
 com.techilashots.java9.features.StackWalkingService.databaseService(StackWalkingService.java:30)  
17
 com.techilashots.java9.features.StackWalkingService.persistenceService(StackWalkingService.java:57)  
18
 Java 9 Stack Walker APIShow All Attributes in Stack Frame  
19
 [Bytecode Index] 112  
20
 [Class Name] com.techilashots.java9.features.StackWalkingService  
21
 [Declaring Class] class com.techilashots.java9.features.StackWalkingService  
22
 [File Name] StackWalkingService.java  
23
 [Method Name] StackWalkingService.java  
24
 [Is Native] false  
25
 [Line Number] 38  
26
 [Method to Display On User Interface]  
27
 Old MacDonald had a Farm. In that Farm, He had 3.0 Cows!  
28
 
          
29
 ================================  
30
 
          
31
 11. Spin Wait Hints  
32
 -------------------  
33
 Spin Wait Hints Makes Power Consumption Efficient  
34
 [Uncomment Method Call in Code, To Run (Non-Terminating) Demo]  
35
 
          
36
 ================================  
37
 
          
38
 12. Java Version Naming  
39
 ----------------------  
40
 Java 9 changes the way Java Version String Format  
41
 Version String Changes in Java 9  
42
 Major Version: 9  
43
 Minor Version: 0  
44
 Security Version: 4  
45
 Build Version: Optional[11]  
46
 In Java 9, Version Naming is Major.Minor.Security.Build  
47
 Currently Running in Java Version: 9.0.4+11  
48
 
          
49
 ================================  
50
 
          
51
 13. Enhanced Method Handles  
52
 ---------------------------  
53
 Java 9 has Enhanced Method Handles for Multitude of Operations  
54
 Length of Array using Method Handle is 3  
55
 Array Constructed using Method Handle of Size 3  
56
 Default Value of Primitive Integer using Method Handles is 0  
57
 Default Value of String using Method Handles is null  
58
 Reader/DeveloperLeft as an Exercise for You :-)  
59
 Refer Loop, CountedLoop, DoWhileLoop, WhileLoop, IteratedLoop, TryFinally  
60
 
          
61
 ================================  
62
 
          
63
 14. Variable Handles  
64
 --------------------  
65
 Java 9 Introduces Variable Handles, Different Types for Same Reference  
66
 Java 9 Introduces.... Variable Handles!  
67
 Value using get() in VarHandle: 5  
68
 Set Value using set(), then get() in VarHandle: 21  
69
 Using getAndAdd() in VarHandle, Old Value: 21, New Value: 72  
70
 Get Byte Value, Then Or, using getAndBitwiseOr()  
71
 Old Byte Value: 21; New Byte Value: 127  
72
 
          
73
 ================================  
74
 
          
75
 15. Filter Incoming Serialization Data  
76
 -------------------------------------  
77
 Java 9 Allows Filtering of Serialization Data, through Object Input Filters  
78
 Incoming Serialization Data Verified for Structure and Vulnerabilities  
79
 Customer Details String Follows (Filtered then De-Serialized)  
80
 skp:skp:4240123488889001:1.243223256E7  
81
 
          
82
 ================================  



16. More Concurrency Updates

[Will be Covered In a Separate Article, As there are Many Changes to Cover and Merits an Article on Its Own]

[Note that I will be covering 'Java 9 Modularity — Project Jigsaw' in another Article. The following Topics/Changes with Code Samples will be Covered in that Article]

JEP 261: Module System

JEP 200: The Modular JDK 

JEP 220: Modular Run-Time Images JEP 260: Encapsulate Most Internal APIs  

Happy Coding with Java 9!

Topics:
api, code snippets, java, java 9, java strings

Published at DZone with permission of Sumith Puri , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}