Class SessionManager

java.lang.Object
com.frostwire.jlibtorrent.SessionManager

public class SessionManager extends Object
Central orchestrator for all bittorrent session operations in jlibtorrent.

SessionManager is the primary class for managing torrent downloads and uploads. It wraps the underlying libtorrent session and provides a higher-level Java API for common bittorrent client operations. Every bittorrent application built with jlibtorrent should create exactly one SessionManager instance.

Basic Usage:

 // Create and start the session manager
 SessionManager sm = new SessionManager();
 sm.start();

 // Register for alerts to monitor torrent events
 sm.addListener(new AlertListener() {
     public int[] types() { return null; } // Listen to all alert types

     public void alert(Alert<?> alert) {
         switch (alert.type()) {
             case ADD_TORRENT:
                 System.out.println("Torrent added");
                 break;
             case TORRENT_FINISHED:
                 System.out.println("Download complete!");
                 break;
         }
     }
 });

 // Download a torrent
 TorrentInfo ti = new TorrentInfo(new File("download.torrent"));
 sm.download(ti, new File("/path/to/save"));

 // Later: stop the session
 sm.stop();
 

Key Responsibilities:

  • Session Lifecycle: Starting and stopping the native libtorrent session
  • Torrent Management: Adding, removing, pausing, resuming torrents
  • Event Dispatch: Processing alerts and notifying registered listeners
  • Settings Management: Configuring bandwidth limits, connection limits, etc.
  • Statistics: Tracking session-wide upload/download speeds and totals
  • Metadata Operations: Fetching metadata from magnet links
  • DHT Operations: Distributed Hash Table queries and storage

Threading Model: SessionManager uses a background alert-processing thread to listen for events from the native session. All user-facing method calls are thread-safe through internal locking. However, some operations like block while waiting for the native session to shut down. Avoid calling these from UI threads or other time-critical code paths.

Alert System: The SessionManager continuously processes alerts generated by the native libtorrent engine. Clients register instances to receive notifications about torrent events. The alert system is the primary way to track download progress, handle errors, and respond to network events.

Session Configuration: Call to provide custom configuration, or for defaults. After starting, settings can be modified via . Common settings shortcuts include , , , and .

Accessing Torrents: Use or to look up a torrent by its info-hash. Use to retrieve all currently managed torrents. Each allows you to query torrent status, control playback, and modify files.

Warning - Blocking Operations: The and methods block until the native session is destroyed. This can take several seconds, especially if there are unresponsive trackers. Do not call these methods from GUI event threads or other time-sensitive code. Instead, consider using a dedicated shutdown thread or executor service.

See Also:
  • Constructor Details

    • SessionManager

      public SessionManager(boolean logging)
      Creates a new SessionManager instance.

      After construction, call to initialize the underlying native session. The session will not begin processing torrents or accepting connections until started.

      Parameters:
      logging - if true, enables verbose logging of libtorrent alerts. Useful for debugging. if false, only critical alerts are logged. Default recommended for production.
      See Also:
    • SessionManager

      public SessionManager()
      Creates a new SessionManager instance with default logging disabled.

      Equivalent to calling new SessionManager(false). This is the recommended constructor for most applications.

      See Also:
  • Method Details

    • swig

      public com.frostwire.jlibtorrent.swig.session swig()
      Returns the underlying SWIG-generated native session object.

      This is the raw libtorrent session object for advanced use cases where the high-level jlibtorrent API does not expose required functionality.

      Warning: Direct use of the native session object bypasses jlibtorrent's thread-safety mechanisms and alert routing. Use only if you understand the threading implications.

      Returns:
      the underlying native session, or null if not started
      See Also:
    • addListener

      public void addListener(AlertListener listener)
      Registers an alert listener to receive torrent event notifications.

      The provided will be called whenever the session generates an alert matching its registered types. Multiple listeners can be registered and all matching listeners will be called for each alert.

      Example:

       sm.addListener(new AlertListener() {
           public int[] types() {
               // Return null to listen to all alert types, or an array of specific types
               return new int[] { AlertType.BLOCK_FINISHED.swig(),
                                 AlertType.TORRENT_FINISHED.swig() };
           }
      
           public void alert(Alert<?> alert) {
               if (alert instanceof BlockFinishedAlert) {
                   BlockFinishedAlert a = (BlockFinishedAlert) alert;
                   System.out.println("Block downloaded for: " + a.torrentName());
               }
           }
       });
       

      Listener Lifecycle: Listeners remain registered until explicitly removed with . Listeners are called synchronously from the internal alert-processing thread, so implementations should avoid long-running operations.

      Parameters:
      listener - the listener to register
      See Also:
    • removeListener

      public void removeListener(AlertListener listener)
      Unregisters a previously registered alert listener.

      After removal, the listener will no longer receive notifications. If the listener was not previously registered, this call has no effect.

      Parameters:
      listener - the listener to unregister
      See Also:
    • start

      public void start(SessionParams params)
      Starts the bittorrent session with custom configuration parameters.

      This initializes the underlying native libtorrent session and starts a background thread for processing alerts. Once started, torrents can be added and downloaded.

      Configuration: The provided SessionParams object contains all settings for the session. Default values are applied for any settings not explicitly configured:

      • Max metadata size: 2 MB (prevents malicious torrents with huge metadata)
      • DHT bootstrap nodes: Standard public DHT nodes (if not provided)
      • Port filtering: Blocks connections to low ports (< 1024) except 80 and 443 for web seeding

      Example:

       SessionParams params = new SessionParams();
       SettingsPack settings = params.getSettings();
       settings.downloadRateLimit(500); // 500 KB/s max download
       settings.uploadRateLimit(200);   // 200 KB/s max upload
       settings.activeDownloads(5);     // Max 5 concurrent downloads
       sm.start(params);
       

      Thread Safety: This method is thread-safe. Calling it multiple times has no effect after the first call.

      Parameters:
      params - the session configuration parameters
      See Also:
    • start

      public void start()
      Starts the bittorrent session with default configuration.

      This is equivalent to calling start(new SessionParams()). Suitable for most applications that don't need custom settings. After starting, settings can be modified with .

      See Also:
    • stop

      public void stop()
      Stops the bittorrent session and releases all resources.

      This method is blocking and will not return until the native libtorrent session has been completely shut down. This can take several seconds, especially if trackers are unresponsive (timeout waiting for tracker announcements).

      What Happens:

      • Posts a final session stats alert for cleanup
      • Waits for alert processing thread to finish
      • Destroys the native session object (may wait for tracker responses)
      • Resets all internal state

      Important: Do NOT call this method from:

      • The GUI/UI event thread (will freeze the interface)
      • AlertListener callbacks (will deadlock)
      • Any time-critical thread

      Best Practice:

       // Stop in a dedicated shutdown thread
       Thread shutdownThread = new Thread(() -> {
           sm.stop();
       });
       shutdownThread.start();
       shutdownThread.join(); // Wait for completion
       

      Calling stop() multiple times is safe (subsequent calls do nothing).

      See Also:
    • restart

      public void restart()
      This method blocks for at least a second plus the time needed to destroy the native session, don't call it from the UI thread.
    • isRunning

      public boolean isRunning()
    • pause

      public void pause()
    • resume

      public void resume()
    • isPaused

      public boolean isPaused()
    • stats

      public SessionStats stats()
    • downloadRate

      public long downloadRate()
    • uploadRate

      public long uploadRate()
    • totalDownload

      public long totalDownload()
    • totalUpload

      public long totalUpload()
    • dhtNodes

      public long dhtNodes()
    • isFirewalled

      public boolean isFirewalled()
    • externalAddress

      public String externalAddress()
    • listenEndpoints

      public List<String> listenEndpoints()
    • settings

      public SettingsPack settings()
      Returns a setting pack with all the settings the current session is working with.

      If the current internal session is null, returns null.

      Returns:
    • applySettings

      public void applySettings(SettingsPack sp)
    • downloadRateLimit

      public int downloadRateLimit()
    • downloadRateLimit

      public void downloadRateLimit(int limit)
    • uploadRateLimit

      public int uploadRateLimit()
    • uploadRateLimit

      public void uploadRateLimit(int limit)
    • maxActiveDownloads

      public int maxActiveDownloads()
    • maxActiveDownloads

      public void maxActiveDownloads(int limit)
    • maxActiveSeeds

      public int maxActiveSeeds()
    • maxActiveSeeds

      public void maxActiveSeeds(int limit)
    • maxConnections

      public int maxConnections()
    • maxConnections

      public void maxConnections(int limit)
    • maxPeers

      public int maxPeers()
    • maxPeers

      public void maxPeers(int limit)
    • listenInterfaces

      public String listenInterfaces()
    • listenInterfaces

      public void listenInterfaces(String value)
    • postSessionStats

      public void postSessionStats()
      This function will post a object, containing a snapshot of the performance counters from the internals of libtorrent.
    • postDhtStats

      public void postDhtStats()
      This will cause a to be posted.
    • postTorrentUpdates

      public void postTorrentUpdates()
      This functions instructs the session to post the StateUpdateAlert, containing the status of all torrents whose state changed since the last time this function was called.

      Only torrents who has the state subscription flag set will be included.

    • isDhtRunning

      public boolean isDhtRunning()
    • startDht

      public void startDht()
    • stopDht

      public void stopDht()
    • find

      public TorrentHandle find(Sha1Hash sha1)
    • find

      public TorrentHandle find(Sha256Hash sha256)
    • find

      public TorrentHandle find(TorrentInfo torrentInfo)
    • getTorrentHandles

      public TorrentHandle[] getTorrentHandles()
      Returns an array of torrent handles to all the torrents currently in the session. Similar to libtorrent's session.get_torrents() method.

      If the session is not initialized, returns an empty array.

      Returns:
      an array of TorrentHandle objects
    • download

      public void download(TorrentInfo ti, File saveDir, File resumeFile, Priority[] priorities, List<TcpEndpoint> peers, com.frostwire.jlibtorrent.swig.torrent_flags_t flags)
      Downloads a torrent with full control over all download parameters.

      This is the most flexible download method, allowing specification of file priorities, peer list, flags, and resume data. For simpler cases, see .

      How It Works:

      • If a torrent with the same info-hash is already being downloaded, file priorities are updated and the method returns (no duplicate torrent)
      • If resume data is provided, the download state is restored from that file
      • Initial peers can be pre-populated (useful for private torrents)
      • Torrent flags control behavior (e.g., UPLOAD_MODE, AUTO_MANAGED, etc.)
      • Torrents are added asynchronously; check for ADD_TORRENT alerts to confirm

      Example:

       TorrentInfo ti = new TorrentInfo(torrentFile);
       File saveDir = new File("/path/to/downloads");
       File resumeFile = new File("/path/to/resume/data.resume");
       Priority[] priorities = new Priority[] {
           Priority.NORMAL,    // file 0: download
           Priority.IGNORE,    // file 1: skip
           Priority.NORMAL     // file 2: download
       };
      
       sm.download(ti, saveDir, resumeFile, priorities, null, new torrent_flags_t());
       

      Resume Data: Resume files are generated by TorrentHandle.saveResumeData(). When provided, they allow instant resume without checking all downloaded pieces.

      Peers: Providing initial peers is useful for private torrents where peer discovery may be limited.

      Parameters:
      ti - the torrent metadata (from .torrent file or magnet link)
      saveDir - directory where files will be saved
      resumeFile - optional resume data file for resuming incomplete downloads
      priorities - optional array of file priorities (must match number of files in torrent)
      peers - optional list of initial peer addresses
      flags - optional torrent flags (e.g., UPLOAD_MODE, AUTO_MANAGED, etc.)
      Throws:
      IllegalArgumentException - if torrent info is invalid or priorities array length doesn't match file count
      See Also:
    • download

      public void download(String magnetUri, File saveDir, com.frostwire.jlibtorrent.swig.torrent_flags_t flags)
      Downloads a magnet uri.
      Parameters:
      magnetUri - the magnet uri to download
      saveDir - the path to save the downloaded files
    • download

      public void download(TorrentInfo ti, File saveDir)
      Parameters:
      ti -
      saveDir -
    • remove

      public void remove(TorrentHandle th, com.frostwire.jlibtorrent.swig.remove_flags_t options)
    • remove

      public void remove(TorrentHandle th)
    • fetchMagnet

      public byte[] fetchMagnet(String uri, int timeout, File tempDir)
      Parameters:
      uri - magnet uri
      timeout - in seconds
      Returns:
      the bencoded info or null
    • dhtGetItem

      public Entry dhtGetItem(Sha1Hash sha1, int timeout)
      Parameters:
      sha1 -
      timeout - in seconds
      Returns:
      the item
    • dhtPutItem

      public Sha1Hash dhtPutItem(Entry entry)
      Parameters:
      entry - the data
      Returns:
      the target key
    • dhtGetItem

      public SessionManager.MutableItem dhtGetItem(byte[] key, byte[] salt, int timeout)
    • dhtPutItem

      public void dhtPutItem(byte[] publicKey, byte[] privateKey, Entry entry, byte[] salt)
    • dhtGetPeers

      public ArrayList<TcpEndpoint> dhtGetPeers(Sha1Hash sha1, int timeout)
      Parameters:
      sha1 -
      timeout - in seconds
      Returns:
      the peer list or an empty list
    • dhtAnnounce

      public void dhtAnnounce(Sha1Hash sha1, int port, int flags)
    • dhtAnnounce

      public void dhtAnnounce(Sha1Hash sha1)
    • moveStorage

      public void moveStorage(File dir)
      Parameters:
      dir -
    • saveState

      public byte[] saveState()
    • reopenNetworkSockets

      public void reopenNetworkSockets()
      Instructs the session to reopen all listen and outgoing sockets.

      It's useful in the case your platform doesn't support the built in IP notifier mechanism, or if you have a better more reliable way to detect changes in the IP routing table.

    • magnetPeers

      public String magnetPeers()
    • lastAlertError

      public Throwable lastAlertError()
      This methods return the last error recorded calling the alert listeners.
      Returns:
      the last alert listener exception registered (or null)
    • onBeforeStart

      protected void onBeforeStart()
    • onAfterStart

      protected void onAfterStart()
    • onBeforeStop

      protected void onBeforeStop()
    • onAfterStop

      protected void onAfterStop()
    • onApplySettings

      protected void onApplySettings(SettingsPack sp)