• Post Reply Bookmark Topic Watch Topic
  • New Topic

ByteBuffer optional methods  RSS feed

 
Ron Aronica
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The ByteBuffer docs describe many of its methods as 'optional operation.' I cannot find a definition for 'optional operation.' What does this mean, and are there portability problems with these methods?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Optional methods are found in many classes in the standard APIs. If you attempt to invoke an optional method using an instance that does not support it, an UnsupportedOperationException is thrown. How do you know if an instance supports a given method? This depends on the class, but generally it's determined by how the instance was created. You can consult the API for the particular classes involved for more info.
In the case of ByteBuffer, the relevant explanations are mostly hidden in the API for the Buffer superclass. Methods like put() are optional, because some buffers are read-only. If you get a buffer from a source that creates read-only buffers, then you'll get an UnsupportedOperationException (more specifically, ReadOnlyException) if you invoke one of the put() methods. As an example - if you create a FileInputStream and invoke getChannel() to get the associated FileChannel, you get a read-only FileChannel. If you then invoke map() to get a MappedByteBuffer, you get a read-only MappedByteBuffer, and put() is not supported.
Generally portability is not an issue with optional methods - that is, it's usually your code that determines whether a given instance will support a given method. You just have to dig through the API until you find the rules under which a particular optional method operates. There may be some optional methods which are platform-dependent - particularly in java.nio, which is much more closely tied to native platform implementations than java.io was. But I don't know of any offhand.
 
Ron Aronica
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jim,
That is a great explaination. Thanks!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!