> ## Documentation Index
> Fetch the complete documentation index at: https://docs.abbyy.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Using Java with FRE for Windows

<Note>
  This topic applies to FRE for Windows .
</Note>

## Adding FineReader Engine library to a Java project

ABBYY FineReader Engine includes a com.abbyy.FREngine-%BUILD\_ID%.jar file, which contains the Java class library for FineReader Engine. You can find it in the [Inc](/fine-reader/engine/distribution/distribution-windows/distribution-kit#incsamples)\\**Java** folder. The path to this file can be specified in the classpath parameter in the command line and in project settings in different Java development environments. Example:

```csharp theme={null}
%JDK%\bin\Javac -classpath <path>/com.abbyy.FREngine-%BUILD_ID%.jar Hello.java
```

%JDK% is the path to Java Development Kit.

<Warning>
  See the list of supported Java Development Kits in [System Requirements](/fine-reader/engine/specifications/system-requirements#jdk_requirements).
</Warning>

## Loading and unloading FineReader Engine

You can use the static Engine class to load the [Engine](/fine-reader/engine/api-reference/engine-object-iengine-interface) object.

The Engine class provides methods that correspond to the ABBYY FineReader Engine [functions](/fine-reader/engine/api-reference/functions) for loading and unloading the Engine:

| Function                                                                                      | Engine class method | The signature of the Engine class method                                                                                                                                                                                         |
| --------------------------------------------------------------------------------------------- | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [InitializeEngine](/fine-reader/engine/api-reference/functions/initializeengine-function)     | InitializeEngine    | `csharp static public IEngine InitializeEngine( String dllFolder, String customerProjectId, String licensePath, String licensePassword, String dataFolder, String tempFolder, boolean isSharedCPUCoresMode ) throws Exception; ` |
| [DeinitializeEngine](/fine-reader/engine/api-reference/functions/deinitializeengine-function) | DeinitializeEngine  | `static public void DeinitializeEngine() throws Exception;`                                                                                                                                                                      |

<Accordion title="Sample code">
  ```csharp theme={null}
  import com.abbyy.FREngine.*;
  public class Hello {
      public static void main( String[] args )
      {
          try {
              // Load the Engine with Online License
              engine = Engine.InitializeEngine( dllPath, customerProjectId, LicensePath, LicensePassword, "", "", false );
              try {
                  // Load a predefined profile
                  engine.LoadPredefinedProfile( "DocumentConversion_Accuracy" );
                  // Process images
                  IFRDocument document = engine.CreateFRDocument();
                  ...
              } finally {
                  engine = null;
                  System.runFinalization();
                  Engine.DeinitializeEngine();
              }
          } catch( Exception ex ) {
              trace( ex.getMessage() );
          }
      }
      private IEngine engine = null;
  ...
  }
  ```
</Accordion>

To load Engine by means of COM, use its GetEngineInprocLoader or GetEngineOutprocLoader methods. See the description of the [IEngineLoader](/fine-reader/engine/api-reference/engine-loaders/iengineloader) interface for details. If you use the GetEngineOutprocLoader method for loading, you do not need to call the [IHostProcessControl::SetClientProcessId](/fine-reader/engine/api-reference/engine-loaders/ihostprocesscontrol/setclientprocessid-method) method as the parent process will be set automatically.

<Warning>
  If you develop your application on Windows but intend running it on Linux, do not use these methods for loading Engine . Use only the InitializeEngine method described above. This limitation is due to the fact that objects implementing IEngineLoader are not available on Linux.
</Warning>

<Accordion title="Sample code using InprocLoader">
  ```csharp theme={null}
  import com.abbyy.FREngine.*;
  // Loading Engine with Online License
  engineLoader = Engine.GetEngineInprocLoader();
  engine = engineLoader.InitializeEngine( customerProjectId, LicensePath, LicensePassword, "", "", false );
  ...
  // Unloading Engine
  engine = null;
  System.runFinalization();
  engineLoader.ExplicitlyUnload();
  engineLoader = null;
  System.runFinalization();
  ```
</Accordion>

<Accordion title="Sample code using OutprocLoader">
  ```csharp theme={null}
  import com.abbyy.FREngine.*;
  // Loading Engine with Online License
  engineLoader = Engine.GetEngineOutprocLoader();
  engine = engineLoader.InitializeEngine( customerProjectId, LicensePath, LicensePassword, "", "", false );
  ...
  // Unloading Engine
  engine = null;
  System.runFinalization();
  engineLoader.ExplicitlyUnload();
  engineLoader = null;
  System.runFinalization();
  ```
</Accordion>

For working with the Engine object created via an engine loader, the Engine class provides the methods which call the corresponding COM functions to marshal the interface pointer across threads:

| Method             | Signature                                            | Comment                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| ------------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| MarshalInterface   | `long MarshalInterface();`                           | Calls the CoMarshalInterface COM function to marshal the [IEngine](/fine-reader/engine/api-reference/engine-object-iengine-interface) interface. This method should be called on the thread where the engine was created, to ensure that the data needed for creating a proxy object on another thread will be available. Returns the handle to the marshaling data.                                                                        |
| UnmarshalInterface | `csharp IEngine UnmarshalInterface( long handle ); ` | Calls the CoUnmarshalInterface COM function to unmarshal the [IEngine](/fine-reader/engine/api-reference/engine-object-iengine-interface) interface, i.e., create a proxy object with which the client process will be able to interact in the same way as with the engine itself. Takes the handle to the marshaling data (returned by the MarshalInterface method) as the input parameter and returns a pointer to the IEngine interface. |

<Note>
  The com.abbyy.FREngine-%BUILD\_ID%.jar file is a self-unpacking archive which is unpacked on your machine the first time you use FineReader Engine Java API. The default folder where the contents are unpacked is [Inc](/fine-reader/engine/distribution/distribution-windows/distribution-kit#incsamples)\Java for Windows. If you need to use another folder, call the Engine.SetJNIDllFolder method before loading the Engine by any of the methods described above. To find out which folder is currently set for unpacking the archive, call the Engine.GetJNIDllFolder .
</Note>

## Using Engine in multi-threaded Java applications

For multi-threaded Java applications you can use the EnginesPool class, which provides a complete solution for creating and managing a pool of FineReader Engine objects. This class implements the java.lang.Runnable interface.

```java theme={null}
public class EnginesPool implements Runnable;
```

Methods of the EnginesPool class are listed below.

| Method                   | Signature                                                                                                                                                                                                                      | Comment                                                                                                                                                                                                                                                                                                                      |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| constructor              | `public EnginesPool( int enginesCount, int waitingEngineTimeout, String customerProjectId, String licensePath, String licensePassword, String dataFolder, String tempFolder, boolean isSharedCPUCoresMode ) throws Exception;` | Creates a new pool of enginesCount Engines. The waitingEngineTimeout sets the timeout for EnginesPool.GetEngine. Other parameters are the same as in [InitializeEngine](/fine-reader/engine/api-reference/functions/initializeengine-function)                                                                               |
| GetEngine                | `csharp public IEngine GetEngine() throws Exception; `                                                                                                                                                                         | Gets an Engine instance from the pool. Throws an exception if waitingEngineTimeout is exceeded.                                                                                                                                                                                                                              |
| ReleaseEngine            | `csharp public void ReleaseEngine( IEngine engine, boolean isRecycleRequired ) throws Exception; `                                                                                                                             | Returns an Engine instance to the pool. If isRecycleRequired is true, deletes this instance and replaces it with a new one (even if the usage limit is not reached, or automatic recycle is disabled).                                                                                                                       |
| SetAutoRecycleUsageCount | `public void SetAutoRecycleUsageCount( int value );`                                                                                                                                                                           | Set how many times a single Engine instance in this pool can be re-used until the instance is recycled: deleted and replaced with a new one automatically. The count can be set to 0 to never recycle automatically (only manual recycling will be possible, via ReleaseEngine). Default is 0 (never recycle automatically). |
| GetAutoRecycleUsageCount | `public int GetAutoRecycleUsageCount();`                                                                                                                                                                                       | Get the Engine instance re-use limit for this pool.                                                                                                                                                                                                                                                                          |
| UnloadEngines            | `public void UnloadEngines() throws Exception;`                                                                                                                                                                                | Unload all Engines and deinitialize the pool.                                                                                                                                                                                                                                                                                |

See the [EnginesPool](/fine-reader/engine/guided-tour/samples#enginespool) code sample for an example of using the EnginesPool class.

## Handling errors

ABBYY FineReader Engine can throw the exceptions of the following types:

* java.lang.OutOfMemoryError
* com.abbyy.FREngine.EngineException

The com.abbyy.FREngine.EngineException exception inherits from the java.lang.Exception and contains one additional method int getHResult, which returns the HRESULT code of the error that occurred. For an exception of this type, you can not only retrieve the error message using the getMessage() method but also retrieve the error code.

```
try {
    ...
} catch( Exception ex ) {
    displayMessage( "Message = " + ex.getMessage() );
    if( ex instanceof EngineException ) {
        displayMessage( "HResult = " + Integer.toString( ( ( EngineException )ex ).getHResult() ) );
    }
}
```

## Calling methods with out-parameters

There are several methods in ABBYY FineReader Engine API which have out-parameters that receive a new value after the method call and must be passed by reference. These parameters are marked in the type library and in descriptions of methods in this Developer's Help as \[out] or \[in, out].

When working with ABBYY FineReader Engine in Java, you have to use a special Ref class to pass a parameter by reference. See examples below.

Example in which the out-parameters are passed by reference to the [IFRPage::FindPageSplitPosition](/fine-reader/engine/api-reference/document-related-objects/frpage/findpagesplitposition-method) method:

<Accordion title="Sample code for out-parameters">
  ```
  Ref<PageSplitDirectionEnum> _ps = new Ref<PageSplitDirectionEnum>();
  Ref<Integer> _start = new Ref<Integer>();
  Ref<Integer> _end = new Ref<Integer>();
  page.FindPageSplitPosition( null, null, _ps, _start, _end );
  PageSplitDirectionEnum ps = _ps.get();
  Integer start = _start.get();
  Integer end = _end.get();
  ```
</Accordion>

Example in which the in/out parameters are passed by reference to the [ICoordinatesConverter::ConvertCoordinates](/fine-reader/engine/api-reference/image-related-objects/coordinatesconverter/convertcoordinates-method) method:

<Accordion title="Sample code for in/out parameters">
  ```
  Ref<Integer> _x = new Ref<Integer>( 100 );
  Ref<Integer> _y = new Ref<Integer>( 200 );
  cnv.ConvertCoordinates( ImageTypeEnum.IT_Modified, ImageTypeEnum.IT_Base, _x, _y );
  Integer x = _x.get();
  Integer y = _y.get();
  ```
</Accordion>

The following example shows the array out-parameters passed by reference to the [IPlainText::GetCharacterData](/fine-reader/engine/api-reference/text-related-objects/plaintext/getcharacterdata-method) method:

<Accordion title="Sample code for array out-parameters">
  ```
  Ref<int[]> _leftBorders = new Ref<int[]>();
  Ref<int[]> _topBorders = new Ref<int[]>();
  Ref<int[]> _rightBorders = new Ref<int[]>();
  Ref<int[]> _bottomBorders = new Ref<int[]>();
  Ref<int[]> _confidences = new Ref<int[]>();
  Ref<boolean[]> _isSuspicious = new Ref<boolean[]>();
  plainText.GetCharacterData( _pageNumbers, _leftBorders, _topBorders, _rightBorders, _bottomBorders, _confidences, _isSuspicious );
  int[] pageNumbers = _pageNumbers.get();
  int[] leftBorders = _leftBorders.get();
  int[] topBorders = _topBorders.get();
  int[] rightBorders = _rightBorders.get();
  int[] bottomBorders = _bottomBorders.get();
  int[] confidences = _confidences.get();
  boolean[]isSuspicious = _isSuspicious.get();
  Ref<int[]> _pageNumbers = new Ref<int[]>();
  ```
</Accordion>

## Collecting garbage

FineReader Engine supports working with the AutoCloseable interface, which allows you to use the try statement to access the resources allocated for objects. It means that once the try block reaches the end, all allocated resources will be closed automatically, without explicitly calling closure methods. We recommend that you use the try statement for all objects in your code (see the example below):

<Accordion title="Sample code">
  ```csharp theme={null}
  try( IFRDocument document = engine.CreateDocument() )
   {
    // Add image to a document
    document.AddImageFile( imagePath, null, null );
    ...
    // Save results to PDF
    document.Export( pdfExportPath, FileExportFormatEnum.FEF_PDF, pdfParams );
   }
  ```
</Accordion>

Working with HGLOBAL

Some of the methods in ABBYY FineReader Engine API take as an input parameter an HGLOBAL handle to a memory block (passed as [\_\_int64](/fine-reader/engine/guided-tour/advanced-techniques/programming-aspects/working-with-properties)). As HGLOBAL is a Windows-specific entity, in Java wrapper these methods receive instead the contents of the memory block as byte\[]. See the list of these methods:

* [LoadImageDocFromMemory](/fine-reader/engine/api-reference/engine-object-iengine-interface/processing-methods/loadimagedocfrommemory-method), [OpenImageFileFromMemory](/fine-reader/engine/api-reference/engine-object-iengine-interface/processing-methods/openimagefilefrommemory-method) methods of the [Engine](/fine-reader/engine/api-reference/engine-object-iengine-interface) object
* [LoadFromMemory](/fine-reader/engine/api-reference/supplementary-objects-and-methods/loadfrommemory-method) method provided by many objects
* [AddImageFileFromMemory](/fine-reader/engine/api-reference/document-related-objects/frdocument/addimagefilefrommemory-method) method of the [FRDocument](/fine-reader/engine/api-reference/document-related-objects/frdocument) object
* [AddFromMemory](/fine-reader/engine/api-reference/document-related-objects/pdfattachments/addfrommemory-method) method of the [PDFAttachments](/fine-reader/engine/api-reference/document-related-objects/pdfattachments) object

On the other hand, the methods which return a [Handle](/fine-reader/engine/api-reference/supplementary-objects-and-methods/handle) object return it in Java wrapper as well.

## Working with enumerations

Methods and properties which accept a combination of enumeration constants require the int value to be passed to the method/property. To obtain the int value of an enumeration constant, use the getValue method which is supported by all enumerations.

Here is sample code showing how to set the [BwPictureFormats](/fine-reader/engine/api-reference/parameter-objects/export-parameters/pdfpicturecompressionparams#bwpictureformats) property of the [PDFPictureCompressionParams](/fine-reader/engine/api-reference/parameter-objects/export-parameters/pdfpicturecompressionparams) object:

```
IPDFExportParams pep = engine.CreatePDFExportParams();
IPDFPictureCompressionParams ppcp = pep.getPictureCompressionParams();
ppcp.setBwPictureFormats(BwPictureFormatsEnum.BWPF_Auto.getValue());
```

See also

[Different Ways to Load the Engine Object](/fine-reader/engine/guided-tour/advanced-techniques/programming-aspects/different-ways-to-load-engine) for Windows

[Cross-platform development in Java](/fine-reader/engine/guided-tour/advanced-techniques/programming-aspects/cross-platform-development-in-java) for Windows
